java代码 个人聊天室1. 可使用文字聊天 2. 可以发送文件 3. 可以私聊
时间: 2024-02-22 15:59:39 浏览: 149
好的,下面是一个简单的Java代码示例,实现了个人聊天室的以下功能:
1. 可以使用文字聊天
2. 可以发送文件
3. 可以私聊
服务端代码:
```java
import java.io.*;
import java.net.*;
import java.util.*;
public class Server {
private static List<ClientHandler> clients = new ArrayList<>();
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(8000);
System.out.println("Server started.");
while (true) {
Socket socket = server.accept();
System.out.println("Client connected: " + socket);
ClientHandler clientHandler = new ClientHandler(socket);
clients.add(clientHandler);
clientHandler.start();
}
}
public static void broadcast(String message, ClientHandler sender) {
for (ClientHandler client : clients) {
if (client != sender) {
client.sendMessage(message);
}
}
}
public static void sendPrivateMessage(String message, String recipient, ClientHandler sender) {
for (ClientHandler client : clients) {
if (client.getUsername().equals(recipient)) {
client.sendMessage("[" + sender.getUsername() + "]: " + message);
}
}
}
public static void removeClient(ClientHandler clientHandler) {
clients.remove(clientHandler);
}
}
class ClientHandler extends Thread {
private Socket socket;
private BufferedReader in;
private PrintWriter out;
private String username;
public ClientHandler(Socket socket) throws IOException {
this.socket = socket;
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
}
@Override
public void run() {
try {
out.println("Enter your username:");
username = in.readLine();
out.println("Welcome, " + username + "!");
String input;
while ((input = in.readLine()) != null) {
if (input.startsWith("/private")) {
String[] tokens = input.split(" ");
String recipient = tokens[1];
String message = input.substring(recipient.length() + 10);
Server.sendPrivateMessage(message, recipient, this);
} else if (input.startsWith("/file")) {
String[] tokens = input.split(" ");
String recipient = tokens[1];
String filename = tokens[2];
int fileSize = Integer.parseInt(tokens[3]);
byte[] fileData = new byte[fileSize];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(filename);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = is.read(fileData, 0, fileData.length);
bos.write(fileData, 0, bytesRead);
bos.flush();
bos.close();
Server.sendPrivateMessage("[File: " + filename + " received]", recipient, this);
} else {
Server.broadcast("[" + username + "]: " + input, this);
}
}
} catch (IOException e) {
System.err.println("Error handling client: " + e);
} finally {
try {
socket.close();
} catch (IOException e) {
System.err.println("Error closing socket: " + e);
}
Server.removeClient(this);
}
}
public void sendMessage(String message) {
out.println(message);
}
public String getUsername() {
return username;
}
}
```
客户端代码:
```java
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client {
private static String username;
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 8000);
System.out.println("Connected to server.");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
// Read username from console and send to server
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your username: ");
username = scanner.nextLine();
out.println(username);
String serverMessage;
while ((serverMessage = in.readLine()) != null) {
System.out.println(serverMessage);
if (serverMessage.startsWith("Welcome,")) {
break;
}
}
// Start a new thread to handle incoming messages from the server
Thread thread = new Thread(new ServerHandler(socket));
thread.start();
// Read messages from console and send to server
while (true) {
String message = scanner.nextLine();
if (message.startsWith("/private")) {
out.println(message);
} else if (message.startsWith("/file")) {
String[] tokens = message.split(" ");
String recipient = tokens[1];
String filename = tokens[2];
File file = new File(filename);
byte[] fileData = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(fileData, 0, fileData.length);
out.println("/file " + recipient + " " + filename + " " + fileData.length);
OutputStream os = socket.getOutputStream();
os.write(fileData, 0, fileData.length);
os.flush();
System.out.println("File sent.");
} else {
out.println(message);
}
}
}
}
class ServerHandler implements Runnable {
private Socket socket;
public ServerHandler(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String serverMessage;
while ((serverMessage = in.readLine()) != null) {
System.out.println(serverMessage);
}
} catch (IOException e) {
System.err.println("Error handling server message: " + e);
}
}
}
```
这个示例代码使用了多线程来处理每个客户端的输入和输出,以及服务器端的广播和私聊消息。你可以在此基础上进行进一步的开发和改进,例如增加用户列表、禁言功能等。
阅读全文