欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java实现P2P通信

程序员文章站 2022-05-21 14:18:54
...

区块链中的消息传播离不p2p通信 

java实现一个简单的p2p通信demo

工具:   idea   jdk1.8   maven

1  :  idea新建maven项目,导入p2p所需要的jar包

    <dependency>
      <groupId>org.java-websocket</groupId>
      <artifactId>Java-WebSocket</artifactId>
      <version>1.3.4</version>



2   :   编写client

import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by jack on 2018/4/1.
 */
public class Client {


    private List<WebSocket> sockets = new ArrayList<WebSocket>();

    public List<WebSocket> getSockets() {
        return sockets;
    }

    public void connectToPeer(String peer) {
        try {
            final WebSocketClient socketClient = new WebSocketClient(new URI(peer)) {
                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    write(this, "客户端连接成功");
                    sockets.add(this);
                }

                @Override
                public void onMessage(String msg) {
                    System.out.println("收到服务端发送的消息:" + msg);
                }

                @Override
                public void onClose(int i, String msg, boolean b) {
                    System.out.println("connection failed");
                    sockets.remove(this);
                }

                @Override
                public void onError(Exception e) {
                    System.out.println("connection failed");
                    sockets.remove(this);
                }
            };
            socketClient.connect();
        } catch (URISyntaxException e) {
            System.out.println("p2p connect is error:" + e.getMessage());
        }
    }

    public void write(WebSocket ws, String message) {
        System.out.println("发送给" + ws.getRemoteSocketAddress().getPort() + "的p2p消息:" + message);
        ws.send(message);
    }

    public void broatcast(String message) {
        if (sockets.size() == 0) {
            return;
        }
        System.out.println("======广播消息开始:");
        for (WebSocket socket : sockets) {
            this.write(socket, message);
        }
        System.out.println("======广播消息结束");
    }
}


3  : 编写server

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by jack on 2018/4/1.
 */
public class Server {



    private List<WebSocket> sockets = new ArrayList<WebSocket>();

    public List<WebSocket> getSockets() {
        return sockets;
    }

    public void initP2PServer(int port) {
        final WebSocketServer socketServer = new WebSocketServer(new InetSocketAddress(port)) {
            public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) {
                write(webSocket, "服务端连接成功");
                sockets.add(webSocket);
            }

            public void onClose(WebSocket webSocket, int i, String s, boolean b) {
                System.out.println("connection failed to peer:" + webSocket.getRemoteSocketAddress());
                sockets.remove(webSocket);
            }

            public void onMessage(WebSocket webSocket, String msg) {
                System.out.println("接收到客户端消息:" + msg);
                write(webSocket, "服务器收到消息");
                //broatcast("服务器收到消息:" + msg);
            }

            public void onError(WebSocket webSocket, Exception e) {
                System.out.println("connection failed to peer:" + webSocket.getRemoteSocketAddress());
                sockets.remove(webSocket);
            }

            public void onStart() {

            }
        };
        socketServer.start();
        System.out.println("listening websocket p2p port on: " + port);
    }

    public void write(WebSocket ws, String message) {
        System.out.println("发送给" + ws.getRemoteSocketAddress().getPort() + "的p2p消息:" + message);
        ws.send(message);
    }

    public void broatcast(String message) {
        if (sockets.size() == 0) {
            return;
        }
        System.out.println("======广播消息开始:");
        for (WebSocket socket : sockets) {
            this.write(socket, message);
        }
        System.out.println("======广播消息结束");
    }
}



4  : 编写main测试主入口

/**
 * Created by jack on 2018/4/1.
 */
public class Main {

    public static void main(String[] args) {
        Server p2pServer = new Server();
        Client p2pClient = new Client();
        int p2pPort = Integer.valueOf(args[0]);
        // 启动p2p服务端
        p2pServer.initP2PServer(p2pPort);
        if (args.length == 2 && args[1] != null) {
            // 作为p2p客户端连接p2p服务端
            p2pClient.connectToPeer(args[1]);
        }
    }
}


5: 进行配置

单机 main 方法  ---选择  run ----选择  eidt conFigurations----左上角"+"号-----选择application  

java实现P2P通信

java实现P2P通信





6  : 进行测试

          先执行main  当作第一个服务器,  再执行main2 ,当作第二个服务器

java实现P2P通信


得到结果如下    

java实现P2P通信



java实现P2P通信

上一篇: 【Redis】订阅发布

下一篇: Channel