java高级程序设计多人聊天系统
时间: 2023-12-31 19:24:15 浏览: 100
Java高级程序设计多人聊天系统是一款基于Java语言开发的C/S模式软件。它具有登录、注册、客户端、转发、服务器端、群发等功能,并能够记录用户的聊天记录。该系统使用JDBC技术来操作数据库,将聊天记录保存在聊天记录.qq文件中。
以下是一个基于Java Socket的多人聊天程序的源码示例:
```java
// 服务器端代码
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("服务器已启动,等待客户端连接...");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("客户端连接成功!");
// 创建线程处理客户端请求
ServerThread serverThread = new ServerThread(socket);
serverThread.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ServerThread extends Thread {
private Socket socket;
public ServerThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
while (true) {
String message = reader.readLine();
System.out.println("收到客户端消息:" + message);
// 处理客户端消息
String response = "服务器已收到消息:" + message;
writer.write(response);
writer.newLine();
writer.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 客户端代码
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 8888);
System.out.println("连接服务器成功!");
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.print("请输入消息:");
String message = consoleReader.readLine();
// 发送消息给服务器
writer.write(message);
writer.newLine();
writer.flush();
// 接收服务器的响应
String response = reader.readLine();
System.out.println("收到服务器响应:" + response);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
阅读全文