使用TCP+多线程编程方式和DataOutputStream,DataInputStream实现基于Java的Scoket编程
时间: 2024-05-03 13:21:57 浏览: 83
Java的Socket编程是基于TCP协议的,使用TCP多线程编程方式可以实现并发处理多个客户端请求,提高系统的并发处理能力。
以下是使用TCP多线程编程方式和DataOutputStream,DataInputStream实现基于Java的Socket编程的代码示例:
服务端代码:
```java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(1234);
System.out.println("Server started");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("Client connected: " + socket);
Thread t = new Thread(new ClientHandler(socket));
t.start();
}
}
}
class ClientHandler implements Runnable {
private Socket socket;
private DataOutputStream out;
private DataInputStream in;
public ClientHandler(Socket socket) throws IOException {
this.socket = socket;
out = new DataOutputStream(socket.getOutputStream());
in = new DataInputStream(socket.getInputStream());
}
public void run() {
try {
while (true) {
String message = in.readUTF();
System.out.println("Received from client: " + message);
out.writeUTF("Server response: " + message);
}
} catch (IOException e) {
System.out.println("Client disconnected: " + socket);
} 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) throws Exception {
Socket socket = new Socket("localhost", 1234);
System.out.println("Connected to server: " + socket);
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
DataInputStream in = new DataInputStream(socket.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.print("Enter message to send to server: ");
String message = br.readLine();
out.writeUTF(message);
String response = in.readUTF();
System.out.println("Received from server: " + response);
}
}
}
```
以上代码实现了简单的客户端与服务端之间的通信,服务端接收到客户端发送的消息后,返回一个响应消息给客户端。使用多线程编程方式可以支持并发处理多个客户端请求,并提高系统的并发处理能力。
阅读全文