使用java编写一个程序,实现一个简单的网络聊天室,支持多个用户同时在线聊天,以及发送文件和图片等功能。
时间: 2024-03-27 11:40:45 浏览: 74
用java实现的网络聊天室
3星 · 编辑精心推荐
实现网络聊天室需要用到 Socket 编程,下面是一个简单的 Java 代码实现:
```
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
ArrayList<PrintWriter> clientOutputStreams;
public class ClientHandler implements Runnable {
BufferedReader reader;
Socket sock;
public ClientHandler(Socket clientSocket) {
try {
sock = clientSocket;
InputStreamReader isReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(isReader);
} catch(Exception ex) { ex.printStackTrace(); }
}
public void run() {
String message;
try {
while ((message = reader.readLine()) != null) {
System.out.println("read " + message);
tellEveryone(message);
}
} catch(Exception ex) { ex.printStackTrace(); }
}
}
public static void main (String[] args) {
new ChatServer().go();
}
public void go() {
clientOutputStreams = new ArrayList<PrintWriter>();
try {
ServerSocket serverSock = new ServerSocket(5000);
while(true) {
Socket clientSocket = serverSock.accept();
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
clientOutputStreams.add(writer);
Thread t = new Thread(new ClientHandler(clientSocket));
t.start();
System.out.println("got a connection");
}
} catch(Exception ex) { ex.printStackTrace(); }
}
public void tellEveryone(String message) {
Iterator<PrintWriter> it = clientOutputStreams.iterator();
while(it.hasNext()) {
try {
PrintWriter writer = (PrintWriter) it.next();
writer.println(message);
writer.flush();
} catch(Exception ex) { ex.printStackTrace(); }
}
}
}
```
这段代码实现了一个简单的聊天室,客户端连接到服务器时,服务器会创建一个新的线程来处理客户端的消息。当有消息到来时,服务器会广播消息给所有连接到服务器的客户端。
你还需要编写客户端代码来连接到服务器。以下是一个简单的 Java 客户端代码实现:
```
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatClient {
BufferedReader reader;
PrintWriter writer;
Socket sock;
public static void main(String[] args) {
new ChatClient().go();
}
public void go() {
try {
sock = new Socket("127.0.0.1", 5000);
InputStreamReader streamReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(streamReader);
writer = new PrintWriter(sock.getOutputStream());
System.out.println("networking established");
Thread readerThread = new Thread(new IncomingReader());
readerThread.start();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Enter message: ");
String message = scanner.nextLine();
writer.println(message);
writer.flush();
}
} catch (Exception ex) { ex.printStackTrace(); }
}
public class IncomingReader implements Runnable {
public void run() {
String message;
try {
while ((message = reader.readLine()) != null) {
System.out.println("read " + message);
}
} catch (Exception ex) { ex.printStackTrace(); }
}
}
}
```
这段代码实现了一个简单的客户端,它连接到服务器并等待用户输入消息。当用户输入消息时,客户端会将消息发送给服务器。当服务器发送消息时,客户端会读取并将其打印到控制台。
以上代码只是一个简单的实现,你可以根据自己的需求对其进行扩展,例如实现发送文件和图片等功能。
阅读全文