采用套接字技术,设计多线程程序使之能同时与多个客户通讯。 (一)三人聊天(采用TCP、UDP或者广播方式之一) 实现三个人聊天:一个人在自己客户端窗口输入“hello”,回车后另外两个人的客户端窗口都显示“hello”;三个人彼此聊天;三个人可以在不同机器上进行聊天。Java代码实现
时间: 2024-03-16 09:41:32 浏览: 139
很高兴回答你的问题!以下是一个基于Java的多线程聊天程序的实现,采用TCP协议:
服务端代码:
```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("服务器已启动,等待客户端的连接...");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("客户端" + socket.getInetAddress() + "已连接");
new Thread(new ServerThread(socket)).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ServerThread implements Runnable {
private Socket socket;
public ServerThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter writer;
while (true) {
String message = reader.readLine();
if (message == null) {
break;
}
System.out.println("客户端" + socket.getInetAddress() + "说:" + message);
// 将消息发送给所有连接的客户端
for (Socket client : ChatServerManager.clients) {
if (client != null && client != socket) {
writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
writer.write(message + "\n");
writer.flush();
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class ChatServerManager {
public static Socket[] clients = new Socket[3];
}
```
客户端代码:
```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("已连接到服务器");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedReader serverReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// 将自己的socket对象存储到ChatServerManager中,以便在服务端转发消息时使用
for (int i = 0; i < ChatServerManager.clients.length; i++) {
if (ChatServerManager.clients[i] == null) {
ChatServerManager.clients[i] = socket;
break;
}
}
new Thread(new ClientThread(serverReader)).start();
while (true) {
String message = reader.readLine();
writer.write(message + "\n");
writer.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ClientThread implements Runnable {
private BufferedReader reader;
public ClientThread(BufferedReader reader) {
this.reader = reader;
}
@Override
public void run() {
try {
while (true) {
String message = reader.readLine();
if (message == null) {
break;
}
System.out.println("收到消息:" + message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ChatServerManager {
public static Socket[] clients = new Socket[3];
}
```
以上是一个简单的实现,可以在本地或不同机器上的三个客户端之间进行聊天。需要注意的是,如果要在不同机器上进行聊天,需将服务端代码部署到公网服务器上,且客户端需要知道服务器的公网IP地址。
阅读全文