The implementation of the JAVA code of the decentralized P2P service of the BLOCKCHAIN blockchain

Why use decentralization?

Example of loan relationship proof

The problems brought by the centralized lending relationship proof:

  1. The machine hangs, the company goes bankrupt, it gets hacked by hackers, and the loan relationship ceases to exist
  2. The loan relationship involves personal privacy, and centralized institutions will use it for big data analysis. For example, major e-commerce companies will analyze personal preferences based on shopping habits, and then guide profitable business behaviors, but this itself is an invasion of privacy.

The implementation of the JAVA code of the decentralized P2P service of the BLOCKCHAIN ​​blockchain

Decentralization can solve the above problems:

  1. If a decentralized node fails, it has little impact on data loss. The more nodes there are, the harder it is for hackers to attack.
  2. Use sophisticated cryptography to ensure privacy
    The implementation of the JAVA code of the decentralized P2P service of the BLOCKCHAIN ​​blockchain

P2P Concept in Blockchain

P2P (Peer to Peer) peer-to-peer computer or peer-to-peer network, a communication protocol between computers.
The core of p2p:
The core of P2P is that data is stored locally in the client, and through the query of stored information (name, address, block), data can be directly transmitted between terminals. The P2P network decentralizes the data traffic on the network. At the same time, the management point not only does not have the pressure of service capacity, but also only stores the index and link of the data, and is not responsible for the data itself, avoiding the trouble of copyright and management. The IPFS file system is based on p2p (the goal is to replace the existing http), and you can search for relevant URLs on Baidu.
The idea of ​​p2p network implementation:
P2P network is actually a "non-central government" and "tribal" network. The way to join is to log in from the client. Most of them do not need authentication. Your things are voluntary, and you don't have to pay for other people's resources. "The P2P world is harmonious." In order to encourage everyone to contribute more while acquiring, because the more you contribute, the more you can share, the developer uses the file-blocking technology to immediately give the part you just owned to others while you download it. Sharing, of course, this kind of sharing does not have to go through your permission, and according to your performance points, encourage "good" people, reward dedication, you help others, others will help you. Since the protocols of many P2P networks are open, the ways of joining are also very broad, and different P2P networks can also communicate with each other, providing a basis for further information sharing.

  • Java network programming: socket programming, netty programming, websoket programming (a technology after the rise of html5)

    • Network programming, socket programming and netty programming are traditional network programming, (server and client)

      • socket programming is based on BIO
      • netty is NIO based
    • websocket programming
      • Websocket is a protocol specification proposed by html5, refer to rfc6455.
        Websocket stipulates a communication specification. Through a handshake mechanism, a tcp-like connection can be established between the client (browser) and the server (webserver), thereby facilitating communication between c-s. Before the advent of websockets, web interactions were generally short or long connections based on the http protocol.
        WebSocket is a technology generated to solve real-time communication between client and server. The websocket protocol is essentially a tcp-based protocol. It first initiates a special http request through the HTTP/HTTPS protocol for handshake, and then creates a TCP connection for exchanging data. After that, the server and the client communicate in real time through this TCP connection. .
      • Websocket programming is relatively simple

Code implementation of P2P server in blockchain

  • Initialize the websoket server (receive client requests and return messages)
  • Sort out the whole process
    • Service start onStart()
    • connection open onOpen()
    • Process the received message onMessage()
    • Connection close onClose()
    • Exception handling onError()
  /**
     * 初始化websoket服务
     * @author cn.wenwuyi
     * @param port
     */
    public void initP2PServer(int port) {
        /**
         * webSoketServer 初始化
         */
        final WebSocketServer socket = new WebSocketServer(new InetSocketAddress(port)) {
             /**
              * 连接打开
              */
             public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) {
                 write(webSocket, queryChainLatestMsg());
                 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 s) {
                 handleMessage(webSocket, s);
             }
             /**
              * 容错
              */
             public void onError(WebSocket webSocket, Exception e) {
                 System.out.println("connection failed to peer:" + webSocket.getRemoteSocketAddress());
                 sockets.remove(webSocket);
             }
             /**
              * 连接开始
              */
             public void onStart() {

             }
        };
        //soket启动
        socket.start();
        System.out.println("listening websocket p2p port on: " + port);
    }
  • Initialize the websocket client (send messages to the server and receive messages from the server)
    • connection open onOpen()
    • Process the received message onMessage()
    • Connection close onClose()
    • Exception handling onError()
  • Each node is both a server and a client WebsoketServer WebSocketClient
 /**
     * 初始化websoket服务
     * @author cn.wenwuyi
     * @param port
     */
  public void connectToPeer(String peer) {
        try {
            final WebSocketClient socket = new WebSocketClient(new URI(peer)) {
                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    write(this, queryChainLatestMsg());
                    sockets.add(this);
                }

                @Override
                public void onMessage(String s) {
                    handleMessage(this, s);
                }

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

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

    private void write(WebSocket ws, String message) {
        ws.send(message);
    }

Note: Each node (server in the blockchain) is both a server and a client, used to synchronize the data of each node

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325981856&siteId=291194637