HTML5 push with WebSocket complete (tomcat)

Source: Internet
Author: User
Tags end final header socket string split stub apache tomcat

There's a message that's going to be erased in 5 days.

I Northeastern University of Software college junior students, is now looking for internships, qq:1021842556

Using WebSocket and Java completion of the message push function, the server is tomcat7.0, some things are their own thinking, do not know just inappropriate, inappropriate place, but also please forgive me, and pointed out.

In simple terms, customer A can send a message to client B, but there are a lot of places to expand,

Like what

1. If you join the database, a send a message when customer B is not online, the server will be the message in the database, and other customer B online, after the message is sent out to customer B

2. The server can also send messages to any client.

The operating effect of the program screenshot as follows (in Chrome, Sogou, Firefox under test pass): The code will be given at the end of

First we open a browser, display input your name, here I enter soar

In opening a second browser, here I enter bill

This is if I send Hello bill I am soar to bill, click Send

You can see it in another browser.

Websocket

What's 1.websocket?

WebSocket is the technology that is produced to solve the real-time communication between client and server. The essence of this is to create a TCP connection for exchanging data first by shaking the HTTP/HTTPS protocol.

The server then communicates with the client in real time through this TCP connection.

The advantages of 2.websocket

Before we implement push technology, used are polling, at the time interval of the characteristics of the browser automatically issued a request, the server will be the active pull back, in this case, we need to continue to send requests to the server, but HTTP request header is very long, The data contained in it may be only a small value, which takes up a lot of bandwidth and server resources. Consumes a large amount of bandwidth and server resources.

The great thing about the WebSocket API is that servers and clients can push information to each other at any time within a given timeframe. After the connection is established, the server can actively transfer the data to the client.

In addition, the header information exchanged between the server and the client is small.

WebSocket is not limited to Ajax (or XHR) communication because Ajax technology requires a client to initiate a request, and WebSocket servers and clients can push information to each other;

For a detailed introduction of Ajax,comet,websocket, and WebSocket message, you can refer to the http://www.shaoqun.com/a/54588.aspx Web design]ajax, Comet and WebSocket ,

If I had time later, I would have written it.

3. How to use WebSocket

Client

In a browser that supports WebSocket, after the socket is created. You can respond to a socket by onopen,onmessage,onclose that is onerror four event implementations

A simple is an example

var ws = new WebSocket ("ws://localhost:8080");
Ws.onopen = function ()
{
console.log ("open");
Ws.send ("Hello");
Ws.onmessage = function (evt)
{
console.log (evt.data)
};
Ws.onclose = function (evt)
{
console.log ("websocketclosed!");
Ws.onerror = function (evt)
{
console.log ("websocketerror!");

1.var ws = new WebSocket ("ws://localhost:8080");





Request a WebSocket object, which is the address of the server that needs to be connected, as the HTTP protocol uses http://, the WebSocket protocol URL uses the ws://, and the other secure WebSocket protocol uses the wss://start.





Ws.send ("Hello");





is used to send messages to the service side





 





2.ws.onopen = function () {Console.log ("open")};





The OnOpen event is triggered when the WebSocket is successfully created





 





3.ws.onmessage = function (evt) {Console.log (evt.data)};





when the client receives a message from the server, the OnMessage event is triggered, and the parameter evt.data contains the data that the server transmits





 





4.ws.onclose = function (evt) {console.log ("websocketclosed!");





The OnClose event is triggered when the client receives a request for a shutdown connection sent by the server





 





5.ws.onerror = function (evt) {console.log ("websocketerror!");





If a connection occurs, processing, receiving, and sending data fails, the OnError event is triggered





we can see that all operations are triggered by events, so that the UI is not blocked, allowing faster response times for the UI and a better user experience.





 





Service End





Now there are a lot of server software support WebSocket, such as Node.js,jetty,tomcat and other





here I'm using Tomat 7.0 and eclipse4.2





use WebSocket under Tomcat first you need to import the associated jar




The WebSocket-related classes provided by
Tomcat7 are located in the package Org.apache.catalina.websocket ( The implementation of package Org.apache.catalina.websocket is contained in file Catalina.jar





 





Here we'll just import all of Tomcat into the line





path->configure build Path->librarise->add library->server runtime->apache Tomcat v7.0





Image





 





 





also need to import the following packages





import Org.apache.catalina.websocket.MessageInbound;


import Org.apache.catalina.websocket.StreamInbound;


import Org.apache.catalina.websocket.WsOutbound;


import Org.apache.catalina.websocket.WebSocketServlet;





 





We need two classes





first for processing WebSocket requests





The second one is used to process each specific WebSocket task





 





First Class








public class Socketserver extends Websocketservlet {


private static final long serialversionuid = 1L;


//......


@Override


protected Streaminbound createwebsocketinbound (String arg0,


httpservletrequest arg1) {


//TODO auto-generated method stub


return new Chatwebsocket (users);


    }


}











this servlet inherits from Websocketservlet and implements the Createwebsocketinbound method. This method returns an instance of the second class.











Second Class








public class Chatwebsocket extends Messageinbound {





@Override


protected void Ontextmessage (Charbuffer message) throws IOException {





        }





@Override


protected void OnOpen (Wsoutbound outbound) {


           


        }





@Override


protected void onClose (int status) {








        }





@Override


protected void Onbinarymessage (Bytebuffer arg0) throws IOException {





        }


//Others slightly





    }











 





protected void Ontextmessage (Charbuffer message) throws IOException {}





Text message response





protected void Onbinarymessage (Bytebuffer arg0) throws IOException {}





Binary Message Response





protected void OnOpen (Wsoutbound outbound) {}





the triggering event of a connection





protected void onClose (int status) {}





the event that is triggered when the connection is closed





 











 





 





4. Program Code





HTML Part








<! DOCTYPE html>


<html>


<head>


<meta charset= "Utf-8" >


<script type= "Text/javascript" src= "Js/jquery.js" ></script>


<script type= "Text/javascript" src= "Js/socket.js" ></script>


<title> Untitled Document </title>


</head>


<script language= "JavaScript" >





</script>


<body>


<table>


<tr>


<td>Message</td>


<td><input type= "text" id= "message" ></td>


</tr>


<tr>


<td>Name</td>


<td><input type= "text" id= "Othername" ></td>


</tr>


<tr>


<td><input id= "Sendbutton" type= "button" value= "Send" onclick= "click" disabled= "true" >


</input></td>


</tr>


</table>


<script>





</script>


</body>


</html>











 





JS section (about the jquery section does not explain)








var username = window.prompt ("Enter your Name:");





document.write ("Welcome<p id=\" username\ ">" +username+ "</p>");





if (!window. WebSocket && windows. Mozwebsocket)


Window. Websocket=window. Mozwebsocket;


if (!window. WebSocket)


alert ("No Support");


var ws;





$ (document). Ready (function () {


   


$ ("#sendbutton"). attr ("disabled", false);


$ ("#sendbutton"). Click (SendMessage);





Startwebsocket ();


})





function SendMessage ()


{


var othername=$ ("#othername"). Val ();


var msg= "msg\t" +username+ "_" +othername+ "_" +$ ("#message"). Val ();


Send (msg);


}


function Send (data)


{


Console.log ("Send:" +data);


ws.send (data);


}


function Startwebsocket ()


{   


ws = New WebSocket ("ws://" + location.host + "/websocket/socketserver");


Ws.onopen = function () {


Console.log ("Success open");


$ ("#sendbutton"). attr ("disabled", false);


    };


ws.onmessage = function (event)


     {


Console.log ("RECEIVE:" +event.data);


Handledata (Event.data);


     };


ws.onclose = function (event) {


Console.log ("Client notified socket has closed", event);


};


 


}





function Handledata (data)


{


var vals=data.split ("T");


var msgtype=vals[0];


switch (msgtype)


    {


case "NAME":


var msg=vals[1];


var mes= "NAME" + "T" +msg+ "_" + username;


Send (MES);


break;


case "MSG":


var Val2s=vals[1].split ("_");


var from=val2s[0];


var message=val2s[2];


Alert (from+ ":" +message);


break;


Default:


break;


           


    }


}











Java Part








import java.io.IOException;


import Java.nio.ByteBuffer;


import Java.nio.CharBuffer;





import javax.servlet.http.HttpServletRequest;


import Java.util.Set;








import Java.util.concurrent.CopyOnWriteArraySet;





import Org.apache.catalina.websocket.MessageInbound;


import Org.apache.catalina.websocket.StreamInbound;


import Org.apache.catalina.websocket.WsOutbound;


import Org.apache.catalina.websocket.WebSocketServlet;











public class Socketserver extends Websocketservlet {


private static final long serialversionuid = 1L;


Public final set<chatwebsocket> users = new copyonwritearrayset<chatwebsocket> ();





public static int usernumber = 1;


@Override


protected Streaminbound createwebsocketinbound (String arg0,


httpservletrequest arg1) {


//TODO auto-generated method stub


return new Chatwebsocket (users);


    }


public class Chatwebsocket extends Messageinbound {





private String username;


Private set<chatwebsocket> users = new copyonwritearrayset<chatwebsocket> ();;





public Chatwebsocket () {





        }





public Chatwebsocket (set<chatwebsocket> users) {


this.users = users;


        }





@Override


protected void Ontextmessage (Charbuffer message) throws IOException {


The text data is processed here


        }





public void OnMessage (String data) {


string[] Val1 = Data.split ("\\t");


if (val1[0].equals ("NAME"))


            {


string[] Val2=val1[1].split ("_");


for (Chatwebsocket user:users) {


if (User.username.equals (Val2[0])) {


User.username=val2[1];


                    }


                }


            }


Else if (val1[0].equals ("MSG"))


            {


string[] Val2=val1[1].split ("_");


for (Chatwebsocket user:users) {


if (user.username.equals (val2[1)) {


try {


charbuffer temp=charbuffer.wrap (data);


User.getwsoutbound (). Writetextmessage (temp);


catch (IOException e) {


//TODO auto-generated catch block


E.printstacktrace ();


                        }


                    }


}       


            }


Else


            {


System.out.println ("ERROR");


            }





        }





@Override


protected void OnOpen (Wsoutbound outbound) {


//This.connection=connection;


This.username = "#" + string.valueof (usernumber);


usernumber++;


try {


String message = "NAME" + "\ T" + this.username;


Charbuffer buffer = charbuffer.wrap (message);


This.getwsoutbound (). writetextmessage (buffer);


} catch (IOException e) {


TODO auto-generated Catch block


E.printstacktrace ();


            }


Users.add (this);


        }





@Override


protected void onClose (int status) {


Users.remove (this);





        }





@Override


protected void Onbinarymessage (Bytebuffer arg0) throws IOException {





        }





    }


   


}


 





explain





here, my idea is
.




1 Each user first needs to enter his or her own name when visiting, and then send a connection request to the server




The
2 server, after accepting a connection request to the client, will new Chatwebsocket (users) to process the request and add it to the online list of users, because at this point the server is unaware of the customer's name. It will give this user a name, #1, and then the server will send "name" + "T" + "#1" to the client, what's your name?





3 Clients receive this message will know that the server is asking their name, so the client will send "name" + "T" + "#1" + "_" + his name to the service side, (my name is XXX)





4 Server received this message based on the current online list of users to find, replace the name of the customer, so that the server will know the name of the customer

5 When the client leaves, the server triggers the OnClose event, and the server removes the current user from the online list

Use the picture to come out like this (bad painting,-_ —!! )

Code





JS





ws = New WebSocket ("ws://" + location.host + "/websocket/socketserver");





 





Connection Service Side





 





Java





protected Streaminbound createwebsocketinbound (String arg0,


httpservletrequest arg1) {


//TODO auto-generated method stub


return new Chatwebsocket (users);


    }





creates a chatwebsocket to handle this request, triggering the OnOpen event of the Chatwebsocket object








@Override


protected void OnOpen (Wsoutbound outbound) {


//This.connection=connection;


This.username = "#" + string.valueof (usernumber);


usernumber++;


try {


String message = "NAME" + "\ T" + this.username;


Charbuffer buffer = charbuffer.wrap (message);


This.getwsoutbound (). writetextmessage (buffer);


} catch (IOException e) {


//TODO auto-generated catch block


E.printstacktrace ();


        }


Users.add (this);


    }











assumes a name for this customer and sends name+ "T" + assumed name to the client and joins the client in the currently connected list of clients





 





JS








function Handledata (data)


{


var vals=data.split ("T");


var msgtype=vals[0];


switch (msgtype)


    {


case "NAME":


var msg=vals[1];


var mes= "NAME" + "T" +msg+ "_" + username;


Send (MES);


break;


.........


    }


}











accepts and processes the message from the service end, discovers that the service side asks what name it is called, and sends "name" + "T" + the assumed name + "_" + the real name to the service end





 





 





Java








public void OnMessage (String data) {


string[] Val1 = Data.split ("\\t");


if (val1[0].equals ("NAME"))


        {


string[] Val2=val1[1].split ("_");


for (Chatwebsocket user:users) {


if (User.username.equals (Val2[0])) {


User.username=val2[1];


                }


            }


        }





//.........


}











handles and accepts the message from the client, discovers that the client replies to its name, and then looks in the list of currently connected clients based on the previously assumed name, turning the kana into the real name





 





JS





function SendMessage ()


{


var othername=$ ("#othername"). Val ();


var msg= "msg\t" +username+ "_" +othername+ "_" +$ ("#message"). Val ();


Send (msg);


}





customer initiates a conversation with another person, the message format is: "MSG" + own name +_+ each other's name +_+ message





 





 





Java








public void OnMessage (String data) {


///............


Else if (val1[0].equals ("MSG"))


        {


string[] Val2=val1[1].split ("_");


for (Chatwebsocket user:users) {


if (user.username.equals (val2[1)) {


try {


charbuffer temp=charbuffer.wrap (data);


User.getwsoutbound (). Writetextmessage (temp);


} catch (IOException e) {


//TODO auto-generated catch block


E.printstacktrace ();


                    }


                }


            }       


        }


///............





    }











discovery is the message sent by the customer, based on the name of each other, in the current list of connected customers look up and send the message to him





 





 





JS








function Handledata (data)


{


var vals=data.split ("T");


var msgtype=vals[0];


switch (msgtype)


    {


///...





case "MSG":


var Val2s=vals[1].split ("_");


var from=val2s[0];


var message=val2s[2];


alert (from+ ":" +message);


break;


Default:


break;


           


    }


}











Found a message from another client that was displayed via alert





 





Java





@Override


protected void onClose (int status) {


Users.remove (this);





        }





found the customer left and removed the customer from the list of connected customers





can improve the place





1. If client A sends a message to B, B is not in line, the message can be stored in the database, when found B online, removed from the database, sent to B





2 service-side to send your name, you can add a time-out mechanism, if the client does not respond to their name within a certain period of time, you can delete the customer from the online list







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.