java实现p2p聊天通信
时间: 2023-11-27 16:06:16 浏览: 134
以下是Java实现P2P聊天通信的步骤:
1. 创建一个服务器,用于客户端之间的通信。服务器需要监听客户端的连接请求,并将客户端的信息存储在一个列表中。
2. 创建一个客户端,用于与其他客户端进行通信。客户端需要向服务器注册自己的信息,包括唯一主键、IP地址和端口号。
3. 当客户端想要与其他客户端进行通信时,它需要向服务器查询目标客户端的信息,包括IP地址和端口号。
4. 客户端通过目标客户端的IP地址和端口号连接到目标客户端,建立通信连接。
5. 一旦连接建立成功,客户端之间就可以通过套接字进行通信,发送和接收消息、图片、音频和视频等文件。
以下是Java实现P2P聊天通信的代码示例:
1. 服务器代码
```java
import java.io.*;
import java.net.*;
import java.util.*;
public class Server {
private static List<ClientInfo> clients = new ArrayList<ClientInfo>();
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("Server started.");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("New client connected: " + socket.getInetAddress().getHostAddress());
ClientInfo clientInfo = new ClientInfo(socket);
clients.add(clientInfo);
Thread thread = new Thread(new ServerHandler(clientInfo, clients));
thread.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ServerHandler implements Runnable {
private ClientInfo clientInfo;
private List<ClientInfo> clients;
public ServerHandler(ClientInfo clientInfo, List<ClientInfo> clients) {
this.clientInfo = clientInfo;
this.clients = clients;
}
public void run() {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(clientInfo.getSocket().getInputStream()));
while (true) {
String message = reader.readLine();
System.out.println("Received message from " + clientInfo.getId() + ": " + message);
if (message.startsWith("REGISTER")) {
String[] parts = message.split(" ");
clientInfo.setId(parts[1]);
clientInfo.setIp(clientInfo.getSocket().getInetAddress().getHostAddress());
clientInfo.setPort(Integer.parseInt(parts[2]));
System.out.println("Registered client " + clientInfo.getId() + " at " + clientInfo.getIp() + ":" + clientInfo.getPort());
} else if (message.startsWith("QUERY")) {
String[] parts = message.split(" ");
String targetId = parts[1];
ClientInfo targetClient = null;
for (ClientInfo client : clients) {
if (client.getId().equals(targetId)) {
targetClient = client;
break;
}
}
if (targetClient != null) {
String response = "CONNECT " + targetClient.getIp() + " " + targetClient.getPort();
PrintWriter writer = new PrintWriter(clientInfo.getSocket().getOutputStream());
writer.println(response);
writer.flush();
System.out.println("Sent response to " + clientInfo.getId() + ": " + response);
} else {
String response = "ERROR Target client not found.";
PrintWriter writer = new PrintWriter(clientInfo.getSocket().getOutputStream());
writer.println(response);
writer.flush();
System.out.println("Sent response to " + clientInfo.getId() + ": " + response);
}
} else {
// Forward message to target client
String[] parts = message.split(" ");
String targetId = parts[0];
ClientInfo targetClient = null;
for (ClientInfo client : clients) {
if (client.getId().equals(targetId)) {
targetClient = client;
break;
}
}
if (targetClient != null) {
PrintWriter writer = new PrintWriter(targetClient.getSocket().getOutputStream());
writer.println(message);
writer.flush();
System.out.println("Forwarded message from " + clientInfo.getId() + " to " + targetClient.getId() + ": " + message);
} else {
String response = "ERROR Target client not found.";
PrintWriter writer = new PrintWriter(clientInfo.getSocket().getOutputStream());
writer.println(response);
writer.flush();
System.out.println("Sent response to " + clientInfo.getId() + ": " + response);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ClientInfo {
private String id;
private String ip;
private int port;
private Socket socket;
public ClientInfo(Socket socket) {
this.socket = socket;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public Socket getSocket() {
return socket;
}
}
```
2. 客户端代码
```java
import java.io.*;
import java.net.*;
public class Client {
private static String id;
private static String ip;
private static int port;
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your ID: ");
id = reader.readLine();
Socket socket = new Socket("localhost", 8888);
System.out.println("Connected to server.");
PrintWriter writer = new PrintWriter(socket.getOutputStream());
writer.println("REGISTER " + id + " 0");
writer.flush();
BufferedReader serverReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String response = serverReader.readLine();
System.out.println("Received response from server: " + response);
if (response.startsWith("CONNECT")) {
String[] parts = response.split(" ");
ip = parts[1];
port = Integer.parseInt(parts[2]);
System.out.println("Connected to client " + id + " at " + ip + ":" + port);
Thread thread = new Thread(new ClientHandler(socket));
thread.start();
while (true) {
String message = reader.readLine();
Socket targetSocket = new Socket(ip, port);
PrintWriter targetWriter = new PrintWriter(targetSocket.getOutputStream());
targetWriter.println(id + " " + message);
targetWriter.flush();
targetSocket.close();
}
} else {
System.out.println("Failed to connect to client " + id);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ClientHandler implements Runnable {
private Socket socket;
public ClientHandler(Socket socket) {
this.socket = socket;
}
public void run() {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (true) {
String message = reader.readLine();
System.out.println("Received message: " + message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
阅读全文