给我代码
时间: 2023-07-10 19:20:10 浏览: 124
好的,这里是一个基于Java Socket的简单多客户端聊天程序的示例代码,仅供参考:
Server端代码:
```java
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class ChatServer {
private ServerSocket serverSocket;
private List<Socket> sockets;
public ChatServer(int port) throws IOException {
serverSocket = new ServerSocket(port);
sockets = new ArrayList<>();
}
public void start() throws IOException {
System.out.println("Server started.");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("New client connected: " + socket);
sockets.add(socket);
new ClientHandler(socket).start();
}
}
private class ClientHandler extends Thread {
private Socket socket;
public ClientHandler(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
while (true) {
String message = Utils.receiveMessage(socket);
System.out.println("Received message: " + message);
broadcast(message);
}
} catch (IOException e) {
System.out.println("Client disconnected: " + socket);
sockets.remove(socket);
}
}
private void broadcast(String message) throws IOException {
for (Socket s : sockets) {
if (s != socket) {
Utils.sendMessage(s, message);
}
}
}
}
public static void main(String[] args) throws IOException {
ChatServer server = new ChatServer(8080);
server.start();
}
}
```
Client端代码:
```java
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
public class ChatClient {
private Socket socket;
public ChatClient(String host, int port) throws IOException {
socket = new Socket(host, port);
}
public void start() {
new Thread(() -> {
try {
while (true) {
String message = Utils.receiveMessage(socket);
System.out.println("Received message: " + message);
}
} catch (IOException e) {
System.out.println("Server disconnected.");
}
}).start();
Scanner scanner = new Scanner(System.in);
while (true) {
String message = scanner.nextLine();
Utils.sendMessage(socket, message);
}
}
public static void main(String[] args) throws IOException {
ChatClient client = new ChatClient("localhost", 8080);
client.start();
}
}
```
Utils类中包含了一些常用的读写操作,这里不再赘述。需要注意的是,这个示例代码中没有对消息格式和协议进行定义,需要根据实际情况进行调整。
阅读全文