简单Socket服务器实现

简单Socket服务器实现

服务端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
* 服务端:
* 1)接收客户端的连接
* 2)接收客户端的数据
* 3)把数据反转,并返回给客户端
* 4)重复2,3步骤,直到客户端发送 'bye',断开连接。
* <p>
* 5)新增支持多个客户端
*/
public class TestServer {

public static void main(String[] args) throws IOException {
// 1、开启服务器
ServerSocket server = new ServerSocket(8989);
ExecutorService executorService = Executors.newCachedThreadPool();

while (true) {
// 2、接收一个客户端的连接
Socket socket = server.accept();
Task task = new Task(socket);
executorService.execute(task);
}
}
}

class Task implements Runnable {
Socket socket;

public Task(Socket socket) {
this.socket = socket;
}

@Override
public void run() {
try {
// 3、先获取输入流和输出流
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();

// 4、转为字符流
InputStreamReader isr = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(isr);

// 处理字符串
String str;
PrintStream ps = new PrintStream(outputStream);
while ((str = bufferedReader.readLine()) != null) {
System.out.println(Thread.currentThread().getName() + ": tick,tick,tick...");
if ("bye".equals(str)) {
ps.println("see you");
break;
}

// 反转
StringBuilder sb = new StringBuilder(str);
sb.reverse();

// 返回给客户端
ps.println(sb.toString());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 断开
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

客户端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* 客户端
* 1)用户输入数据
* 2)发送给服务器
* 3)接收服务器返回的结果
* 4)重复以上步骤,直到输入bye 结束
**/
public class TestClient {
public static void main(String[] args) throws IOException {
// 1. 连接服务器
Socket socket = new Socket("192.168.124.17", 8989);
/**
* 客户端
* 1)用户输入数据
* 2)发送给服务器
* 3)接收服务器返回的结果
* 4)重复以上步骤,直到输入bye 结束
*/
Scanner scanner = new Scanner(System.in);
PrintStream ps = new PrintStream(socket.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));

while (true) {
//获取用户输入
System.out.println("Please print something:");
String word = scanner.nextLine();

// 发送给服务端
ps.println(word);

// 接收服务器返回的数据
String result = br.readLine();
System.out.println("Lucy: " + result);
if ("see you".equals(result)) {
break;
}
}

// 关闭
scanner.close();
socket.close();
}
}
作者

Dench

发布于

2020-08-06

更新于

2020-08-06

许可协议

CC BY-NC-SA 4.0

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×