Java聊天室简易实现代码
时间: 2023-08-14 20:06:36 浏览: 104
一个简单java聊天室代码
5星 · 资源好评率100%
以下是一个简单的Java局域网聊天室的实现代码,包括服务器端和客户端:
服务器端代码:
```
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class ChatServer {
private List<Socket> clients = new ArrayList<>();
private ServerSocket serverSocket;
public ChatServer(int port) {
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
}
public void start() {
System.out.println("Server is running...");
while (true) {
try {
Socket client = serverSocket.accept();
clients.add(client);
new ServerThread(client).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class ServerThread extends Thread {
private Socket client;
private BufferedReader in;
private PrintWriter out;
public ServerThread(Socket client) {
this.client = client;
try {
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
String line;
try {
while ((line = in.readLine()) != null) {
System.out.println("Received message: " + line);
for (Socket c : clients) {
PrintWriter pw = new PrintWriter(c.getOutputStream(), true);
pw.println(line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ChatServer server = new ChatServer(8888);
server.start();
}
}
```
客户端代码:
```
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class ChatClient {
private Socket socket;
private BufferedReader in;
private PrintWriter out;
private String host;
private int port;
public ChatClient(String host, int port) {
this.host = host;
this.port = port;
}
public void start() {
try {
socket = new Socket(host, port);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
new ClientThread().start();
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = stdin.readLine()) != null) {
out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private class ClientThread extends Thread {
public void run() {
String line;
try {
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ChatClient client = new ChatClient("localhost", 8888);
client.start();
}
}
```
需要注意的是,这只是一个简单的实现,还需要考虑一些安全和性能问题,比如数据加密、多线程处理等。
阅读全文