Java Socket

Server.java

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
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8081);
while (true) {
Socket socket = serverSocket.accept();
new Thread(new Runnable() {
@Override
public void run() {
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str = "";
while ((str = bufferedReader.readLine()) != null) {
if (str.equals("1")) {
Thread.sleep(5 * 1000);
}
System.out.println(str);
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
}

Client.java

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 8081);
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
while (true) {
String str = bufferedReader.readLine();
bufferedWriter.write(str);
bufferedWriter.write("\n");
bufferedWriter.flush();
}
}
}

Java Socket源码地址​github.com