java利用Socket通讯原理实现服务器和客户端之间多线程通信的代码
时间: 2024-03-06 18:49:28 浏览: 101
利用 Socket 实现多线程通信
4星 · 用户满意度95%
以下是Java利用Socket通讯原理实现服务器和客户端之间多线程通信的示例代码:
服务器端代码:
```java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("服务器已启动,等待客户端连接...");
while (true) {
Socket socket = serverSocket.accept();
new ServerThread(socket).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ServerThread extends Thread {
private Socket socket;
public ServerThread(Socket socket) {
this.socket = socket;
}
public void run() {
try {
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
PrintWriter pw = new PrintWriter(os);
String line = null;
while ((line = br.readLine()) != null) {
System.out.println("客户端说:" + line);
pw.println("服务端已接收到消息:" + line);
pw.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
客户端代码:
```java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 9999);
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
PrintWriter pw = new PrintWriter(os);
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while ((line = console.readLine()) != null) {
pw.println(line);
pw.flush();
System.out.println("服务端回复:" + br.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
该示例代码实现了一个简单的服务器和客户端之间的多线程通信。服务器端使用ServerSocket监听端口号9999,接收客户端的连接请求,并创建一个新线程处理该客户端的请求。客户端连接服务器端后,使用Socket对象的输入输出流与服务器端进行通信。在通信过程中,服务器端每接收到一条消息就会输出客户端发送的内容,并回复一条消息。客户端使用控制台输入消息,并等待服务器端的回复。
阅读全文