1. Create a MAVEN project
Pom.xml files are as follows
<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > < Modelversion>4.0.0</modelversion> <groupId>cn.hadron</groupId> <artifactid>p2p</ar tifactid> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name> ;p 2p</name> <url>http://maven.apache.org</url> <properties> <project.build.sou rceencoding>utf-8</project.build.sourceencoding> </properties> <dependencies> <de Pendency> <groupId>org.java-websocket</groupId> <artifactid>java-websocket<
;/artifactid> <version>1.3.4</version> </dependency> <dependency> <groupid>junit</groupid> <artifactId>junit</artifactId> <version>4.9</version> <scope>test<
;/scope> </dependency> </dependencies> </project>
2, server-side programs
Package cn.hadron.p2p;
Import java.net.InetSocketAddress;
Import java.util.ArrayList;
Import java.util.List; Import Org.java_websocket.
WebSocket;
Import Org.java_websocket.handshake.ClientHandshake;
Import Org.java_websocket.server.WebSocketServer; /** * * * * * * * * * * * * */public class P2pserver {//all server WebSocket private list<websocket> sockets = new Array
List<websocket> ();
Public list<websocket> Getsockets () {return sockets; /** * Initialize Peer-to-peer server side * @param port:server port number/public void initserver (int port) {/* * * Create a WebSocket service side * Defines a websocketserver anonymous subclass object Socketserver * New Inetsocketaddress (port) is Websocketserver constructor parameter * inetsocketaddress is (IP address + port number) type, namely port address type * * Final websocketserver socket
Server = new Websocketserver (new Inetsocketaddress (port) {/** * Overrides 5 event methods that trigger this method when an event occurs
* * @Override public void OnOpen (WebSocket WebSocket, Clienthandshake clienthandshake) {//Create connection successfully triggers write (WebSocket, "
Service End ");
When a webSocket connection is successfully created, the link is added to the connection pool Sockets.add (webSocket);
@Override public void OnClose (WebSocket WebSocket, int i, String s, Boolean B) {//Disconnect time Trigger System.out.println (websocket.getremotesocketaddress () + "client disconnected from server.
");
When the client disconnects, the WebSocket connection pool deletes the link sockets.remove (webSocket);
@Override public void OnMessage (WebSocket WebSocket, String msg) {//the trigger when the client sends a message
SYSTEM.OUT.PRINTLN ("Receive client message:" + msg);
Write (WebSocket, "received message");
Called @Override public void OnError (WebSocket WebSocket, Exception e) {//connection error, followed by triggering OnClose method System.out.println (websocket.getremotesocketaddress () + "Client link error.
");
Sockets.remove (WebSocket); @Override public void OnStart () {System.out.println ("WebSocket serv
Er-end start ... ");
}
};
Socketserver.start ();
SYSTEM.OUT.PRINTLN ("Monitor socketserver port" + port); /** * Sends messages to client * @param WS * @param message */public void write (WebSocket ws, String Messag
e) {System.out.println ("Send To" + ws.getremotesocketaddress (). Getport () + "Peer-to-peer message:" + messages);
Ws.send (message); /** * broadcasts messages to all clients * @param message */public void Broatcast (String message) {if sockets.
Size () = = 0) {return;
} System.out.println ("= = = = = Broadcast Message begins:");
for (WebSocket socket:sockets) {this.write (sockets, message);
} System.out.println ("end of = = = Broadcast Message");
}
}
3, client programs
Package cn.hadron.p2p;
Import Java.net.URI;
Import java.net.URISyntaxException;
Import java.util.ArrayList;
Import java.util.List; Import Org.java_websocket.
WebSocket;
Import org.java_websocket.client.WebSocketClient;
Import Org.java_websocket.handshake.ServerHandshake; /** * Peer-to-peer Client * * */public class P2pclient {//All client WebSocket connection pool private list<websocket> sockets = new ARR
Aylist<websocket> ();
Public list<websocket> Getsockets () {return sockets; /** * Connects to peer/public void Connectpeer (String peer) {try {/** *
The websocketclient is a abstract class this expects a valid "ws://" URI to connect to.
* When connected, a instance recieves important events related to the life of the connection.
* A subclass must implement OnOpen, OnClose, and onMessage to be useful.
* An instance can send messages to it's connected server via the Send method. * * Create a WebSocket client * * Final websocketclient socketclient = new WebS Ocketclient (New URI (peer)) {@Override public void OnOpen (Serverhandshake serverhandshake)
{Write (this, client open);
Sockets.add (this); @Override public void OnMessage (String msg) {System.out.println ("collection
Message sent to the server: "+ msg"; @Override public void OnClose (int i, String msg, Boolean b) {Syste
M.OUT.PRINTLN ("Client shutdown");
Sockets.remove (this); @Override public void OnError (Exception e) {System.out.println ("customer
End Error ");
Sockets.remove (this);
}
};
The client begins to connect to the server Socketclient.connect (); catch (UrisyntaxexCeption e) {System.out.println ("Connection error:" + e.getmessage ()); }/** * Send message to server * The remote socket address of the current websocket, that is, servers-side * @param WS: * @param messages/P ublic void Write (WebSocket ws, String message) {System.out.println ("sent" + ws.getremotesocketaddress (). Getport ()
+ "Peer-to-peer News:" + message);
Ws.send (message); /** * broadcasts messages to all service ports * @param message/public void Broatcast (String message) {if sockets.
Size () = = 0) {return;
} System.out.println ("= = = = = Broadcast Message begins:");
for (WebSocket socket:sockets) {this.write (sockets, message);
} System.out.println ("end of = = = Broadcast Message");
}
}
4. Entrance procedure
Package cn.hadron.p2p;
/**
* Peer-to-peer Network Each node is a server and client * * * Public
class Main {public
static void Main (string[] args) {
if args= =null| | args.length==0) {
System.out.println ("Main method has no parameters.) ");
return;
}
P2pserver p2pserver = new P2pserver ();
P2pclient p2pclient = new P2pclient ();
int p2pport = integer.valueof (Args[0]);
Start Peer-to-peer service End
P2pserver.initserver (p2pport);
if (args.length = = 2 && args[1]!= null) {
//As Peer-to-peer Client Connection Peer-to-peer service
-side P2pclient.connectpeer (args[1));
}
}
5, build Peer-to-peer network
The basic idea, we through the program running in different port number to simulate the Peer-to-peer network communication of different nodes, that is, one is considered as a node 5.1 configuration 1th node
(1) peer1 naming
(2) peer1 parameter configuration
Peer1 is running on port 7001 as the server side
(3) running Peer1
Peer1 node Output
5.2 Configuration 2nd node
(1) Create Peer2
(2) peer2 parameter configuration
The 2nd node in the Peer-to-peer network, peer2 as server and client, runs on port 7002 as a server and connects to Peer1 as a client via ws://localhost:7001
(3) peer2 node output
Output Description:
The two lines are peer2 as sever output, and the middle three lines are output as client side. The following is an analysis of client-side output:
A peer-to-peer message sent to 7001: The client opens a message sent by the server: The server begins
to receive the message sent by the server: Received message
When the client side executes the Connect () method, Peer2 successfully connects to the OnOpen method of the peer1 that triggers both ends of the connection (the server and client side). The client-side OnOpen method executes the write (this, client open) statement, sending a message to the server side, so the output sends a PEER-TO-PEER message to 7001: The client opens. The server side receives the client-side sent message clients to open, triggers the OnMessage method, and replies to the client side to receive the message, so the client-side output receives the message sent by the server: The message is received. The server-side OnOpen method executes the write (WebSocket, "service-side-fight") statement, sending the message to the client side, so the output receives the message sent by the server: the server is fighting.
Note: The OnOpen method on the server side is preceded by the OnMessage method on the server side.
(4) View Peer1 output Changes
Console switch to Peer1
Found more than 3 lines of information:
A peer-to-peer message sent to 51290: The server begins to
receive a client message: The client opens
a peer-to-peer message sent to 51290: Message received
When Peer2 successfully connects to Peer1, the connection is opened successfully, triggering the OnOpen method at both ends of the connection (the server and client side) . The server-side OnOpen method executes the write (WebSocket, "service-side-fight") statement, outputting the Peer-to-peer message sent to 51290: service-side fighting. The OnOpen method in the client side has a statement write (this, "Client open"), sends a message to the server side, the server-side OnMessage method is triggered, and the output 1 lines receive the client message: the client opens. When a message is received, the server side responds to the message. So the output sends a PEER-TO-PEER message to 51290: The message is received. 5.3 Configuring a third node Peer3
(1) Configure Peer3
The 3rd node in the Peer-to-peer network, Peer3 as server and client, runs on port 7003 as a server and connects to Peer2 as a client via ws://localhost:7002
(2) Start Peer3
(3) View Peer2 output changes