java实现p2p通信
时间: 2023-07-29 14:06:13 浏览: 147
Java 实现 P2P 通信可以使用 Java 的 Socket 编程。下面是一个简单的 P2P 通信的示例代码:
```java
// P2P Server
public class P2PServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8888);
while (true) {
Socket socket = serverSocket.accept();
DataInputStream dis = new DataInputStream(socket.getInputStream());
String message = dis.readUTF();
System.out.println("Received message: " + message);
dis.close();
socket.close();
}
}
}
// P2P Client
public class P2PClient {
public static void main(String[] args) throws IOException {
String host = "localhost";
int port = 8888;
Socket socket = new Socket(host, port);
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
dos.writeUTF("Hello, P2P Server!");
dos.flush();
dos.close();
socket.close();
}
}
```
在这个示例中,P2P 通信的流程大致如下:
1. P2P Server 启动并监听端口 8888。
2. P2P Client 连接 P2P Server。
3. P2P Client 向 P2P Server 发送消息 "Hello, P2P Server!"。
4. P2P Server 接收到消息并输出。
5. P2P Server 关闭连接。
6. P2P Client 关闭连接。
可以看到,P2P 通信的过程中,每个节点都既可以充当服务器,也可以充当客户端,实现了去中心化的通信方式。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![application/pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)