在上面代码的基础上实现一对多
时间: 2024-03-23 20:39:08 浏览: 31
好的,以下是在上面代码的基础上实现一对多通信的 JAVA 代码示例:
服务端代码:
```java
import java.io.*;
import java.net.*;
import java.util.*;
public class Server {
private static final int PORT = 9999;
private static Set<Socket> clients = new HashSet<>();
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("服务端已启动,等待客户端连接...");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("客户端已连接:" + socket.getInetAddress().getHostAddress());
clients.add(socket);
new Thread(new ServerHandler(socket)).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
static class ServerHandler implements Runnable {
private Socket socket;
private BufferedReader reader;
private PrintWriter writer;
public ServerHandler(Socket socket) {
try {
this.socket = socket;
this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.writer = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
while (true) {
String message = reader.readLine();
if (message == null) {
break;
}
System.out.println("客户端说:" + message);
broadcast(message);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
writer.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void broadcast(String message) {
for (Socket client : clients) {
try {
PrintWriter pw = new PrintWriter(client.getOutputStream(), true);
pw.println("客户端说:" + message);
} 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);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
new Thread(() -> {
try {
while (true) {
String response = reader.readLine();
System.out.println(response);
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
while (true) {
System.out.print("请输入消息:");
String message = consoleReader.readLine();
writer.println(message);
}
//reader.close();
//writer.close();
//socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
以上是一个简单的基于 SOCKET 的局域网一对多通信的 JAVA 代码示例。在实际开发过程中,还需要考虑异常处理、线程安全、协议设计等问题,并根据具体需求进行功能扩展。
阅读全文