多线程的Socket通讯实例
时间: 2023-05-31 20:05:17 浏览: 90
以下是一个简单的多线程Socket通讯的实例,其中服务器和客户端之间可以进行简单的字符串通讯。
服务器端代码:
```
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class MultiThreadedServer {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(1234);
while (true) {
Socket socket = serverSocket.accept();
Thread t = new Thread(new ServerThread(socket));
t.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static class ServerThread implements Runnable {
private Socket socket;
public ServerThread(Socket socket) {
this.socket = socket;
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String line;
while ((line = in.readLine()) != null) {
System.out.println("Received: " + line);
out.println("Server received: " + line);
}
in.close();
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
客户端代码:
```
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class MultiThreadedClient {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 1234);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader consoleIn = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = consoleIn.readLine()) != null) {
out.println(line);
System.out.println(in.readLine());
}
in.close();
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
运行这两个程序后,在客户端中输入字符串,服务器会将其原样返回。在服务器端控制台上也可以看到接收到的字符串。
阅读全文