生成一个代码基于TCP协议的聊天程序的设计与实现java
时间: 2023-11-17 17:06:06 浏览: 84
基于TCP的协议的聊天程序
3星 · 编辑精心推荐
好的,以下是一个基于TCP协议的聊天程序的设计与实现Java代码:
1. 服务器端代码
```java
import java.io.*;
import java.net.*;
public class ChatServer {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("Server started.");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("New client connected.");
// 启动一个新线程处理该客户端的请求
new Thread(new ChatHandler(socket)).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ChatHandler implements Runnable {
private Socket socket;
public ChatHandler(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
while (true) {
// 读取客户端发送的消息
String msg = reader.readLine();
if (msg == null) {
// 客户端已断开连接
break;
}
System.out.println("Received: " + msg);
// 将消息发回给客户端
writer.write(msg + "\n");
writer.flush();
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
2. 客户端代码
```java
import java.io.*;
import java.net.*;
public class ChatClient {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 8888);
System.out.println("Connected to server.");
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
while (true) {
// 读取控制台输入的消息
String msg = console.readLine();
// 发送消息给服务器
writer.write(msg + "\n");
writer.flush();
// 读取服务器回复的消息
String reply = reader.readLine();
if (reply == null) {
// 服务器已断开连接
break;
}
System.out.println("Received: " + reply);
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
以上代码实现了一个简单的聊天程序。通过运行ChatServer和多个ChatClient,可以在不同的客户端之间进行聊天。注意,该程序只是一个基本示例,实际应用中还需要进行一些安全性和稳定性的优化。
阅读全文