WebSocket Communication implements Java simulation of a client-to-WebClient communication

Source: Internet
Author: User

Environment:

Tomcat 7

Maven Project

IDE is IDEA2017

Project Function Description:

Starting the project will launch a web-side websocket-client and a Java-emulated websocket-server.

There is also a main class in the project, which is launched separately, simulating the launch of a Java-side websocket-client.

Java-client can send messages to the web side by sending messages to the server instantly.

Look at the JS code on the Web side first, very simple:
 <script type= "Text/javascript" > var  socket = new  WebSocket ("Ws:localhost:8080/websocket/chat" )  var  name = "web"  Socket.onopen  = function   () {Socket.send ( "webinit" + "-" + name)    ; } socket.onmessage  = function   ( Messagemeta) { var  message = Messagemeta. Data document.getElementById ( "Show"). InnerHTML + = "<br>" +message}
    </script> <div id= "show" > Initial sentence </div> 

JS uses WebSocket to establish a link to the server, where the name of the Web is "Web", the OnOpen sends a message to the server, which tells the server the name of the current web, followed by the name.

The onmessage is used to receive messages sent from the server. Append to the Web page.

Look at the server code again, it is also very well understood:

First look at the code is very small, in the form of annotations, in red handwriting 1 to identify the current websocket name.

The Connect () method is executed when an access server is connected. Adds the current Chatan object to the Connections collection. Proceed to the 3-point method. is processed according to the received message. Here's the code at "3":

@OnMessagepublicvoidreceiveMessage (String message) throws IOException {ChatAn ChatAn=NewChatAn ();    SYSTEM.OUT.PRINTLN (message); if(Message.startswith ("Webinit")) {        //web-client The first day the message is automatically sent when the connection is established to name the connection username messages in Webinit-web         This. UserName = Message.split ("-") [1]; SendMessage ( This, "connection establishment");//This sentence is used to feedback the Web-server connection}Else if(Message.startswith ("Javaclient")) {        //receive messages from java-client each connection does not need to be named username ConnectionID         for(inti = 0; I < connections.size (); i++) {            if(Connections.get (i). Username.equals ("Web")) {//ChatAn =Connections.get (i);  Break; }} sendMessage (ChatAn, message.substring ("Javaclient". Length (), Message.length ())); }}

StartsWith ("Webinit") is executed when the Web is connected, only once.

StartsWith ("Javaclient") is a Java-side connection when executed. This will traverse connections to find the Web connection, and then call SendMessage to send a message.

Finally, the point is, see Java How to use WebSocket to simulate the client, there are two classes: the first: Client.java
 PackageSocket1;Importjavax.websocket.*; @ClientEndpoint () Public classClient {@OnOpen Public voidOnOpen (Session session) {} @OnMessage Public voidonMessage (String message) {//Honestly, this method doesn't have to be done .System.out.println ("Client onMessage:" +message); } @OnClose Public voidonClose () {}}
A secondMain.java, very simple, the key to see the method:

 PackageSocket1;ImportJavax.websocket.ContainerProvider;Importjavax.websocket.DeploymentException;Importjavax.websocket.Session;ImportJavax.websocket.WebSocketContainer;ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.net.URI; Public classMain {Private StaticString uri = "Ws://localhost:8080/websocket/chat"; Private StaticSession session; Private voidstart () {Websocketcontainer container=NULL; Try{container=Containerprovider.getwebsocketcontainer (); } Catch(Exception ex) {System.out.println ("Error" +ex); }        Try{URI R=uri.create (URI); Session= Container.connecttoserver (client.class, R); } Catch(Deploymentexception |IOException E)        {E.printstacktrace (); }    }     Public Static voidMain (string[] args) {main client=NewMain ();        Client.start (); BufferedReader BR=NewBufferedReader (NewInputStreamReader (system.in)); String input= ""; Try {             Do{input=Br.readline (); if(!input.equals ("Exit") ) Client.session.getBasicRemote (). SendText ("Javaclient" +input); }  while(!input.equals ("Exit")); } Catch(IOException e) {e.printstacktrace (); }    }}

GitHub Project Address:

Https://github.com/simuhunluo/socket5

WebSocket Communication implements Java simulation of a client-to-WebClient communication

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.