HTML5 WebSocket Example code for Point-to-point chat

Source: Internet
Author: User
Tags getmessage

HTML5 WebSocket and Tomcat to achieve a multi-person chat, it is the simplest is the most basic, in which attention is the development environment, To meet jdk1.7 and tomcat8, of course tom7 7.063 also line, found on the site with Google on the WebSocket point-to-point chat, better can and most systems very good to look at.

Because it is analog, here are two JSP pages A and B, the inside of the session to put two names xiaoming and small, note that the session here is Httpsessionsession, The Session in the previous multiplayer chat was javax.websocket.Session;

Here to think about, using Httpsessionsession control chat users, there is no use of annotations, the traditional web. XML configuration, first call the Initservlet method when the system starts.

publicclassinitservletextendshttpservlet{

privatestaticfinallongserialversionuid=-3163557381361759907l;

privatestatichashmap<string,messageinbound>socketlist;

Publicvoidinit (Servletconfigconfig) throwsservletexception{

initservlet.socketlist=newhashmap<string,messageinbound>;

Super.init (config);

SYSTEM.OUT.PRINTLN ("Initialize chat container");

}

publicstatichashmap<string,messageinbound>getsocketlist{

Returninitservlet.socketlist;

}

}

Here you can integrate with your own system, the corresponding Web configuration code is as follows:

<?xmlversion= "1.0" encoding= "UTF-8"?>

<web-appversion= "3.0" xmlns= "Http://java.sun.com/xml/ns/javaee"

Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"

Xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee

Http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd ">

<servlet>

<servlet-name>websocket</servlet-name>

<servlet-class>socket. Mywebsocketservlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>websocket</servlet-name>

<url-pattern>*.do</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>initServlet</servlet-name>

<servlet-class>socket. Initservlet</servlet-class>

<load-on-startup>1</load-on-startup><!--Method Execution Level--

</servlet>

<welcome-file-list>

<welcome-file>index.jsp</welcome-file>

</welcome-file-list>

</web-app>

This is the most common front desk like the process of sending requests in the background, it is also easy to embed into their own system

Mywebsocketservlet:

publicclassmywebsocketservletextendswebsocketservlet{

Publicstringgetuser (httpservletrequestrequest) {

Stringusername= (String) request.getSession.getAttribute ("User");

if (username==null) {

Returnnull;

}

Returnusername;

}

Protectedstreaminboundcreatewebsocketinbound (STRINGARG0,

Httpservletrequestrequest) {

System.out.println ("User" +request.getsession.getattribute ("username") + "login");

Returnnewmymessageinbound (This.getuser (request));

}

}

Mymessageinbound Inheritance Messageinbound

Packagesocket;

Importjava.io.IOException;

Importjava.nio.ByteBuffer;

Importjava.nio.CharBuffer;

Importjava.util.HashMap;

Importorg.apache.catalina.websocket.MessageInbound;

Importorg.apache.catalina.websocket.WsOutbound;

Importutil. Messageutil;

publicclassmymessageinboundextendsmessageinbound{

Privatestringname;

publicmymessageinbound{

Super

}

Publicmymessageinbound (Stringname) {

Super

This.name=name;

}

@Override

Protectedvoidonbinarymessage (ByteBufferarg0) throwsioexception{

}

@Override

Protectedvoidontextmessage (charbuffermsg) throwsioexception{

Map after the message is processed by the user

Hashmap<string,string>messagemap=messageutil.getmessage (msg);//Processing message Classes

Online User Collection Class map

hashmap<string,messageinbound>usermsgmap=initservlet.getsocketlist;

Stringfromname=messagemap.get ("FromName");//Message from human userid

Stringtoname=messagemap.get ("ToName");//the userid to whom the message is sent

Get the user

Messageinboundmessageinbound=usermsgmap.get (toname);//Remove the Messageinbound from the warehouse

Messageinboundmessagefrominbound=usermsgmap.get (FromName);

if (messageinbound!=null&&messagefrominbound!=null) {//If it is being sent to a person for operation

Wsoutboundoutbound=messageinbound.getwsoutbound;

Wsoutboundoutfrombound=messagefrominbound.getwsoutbound;

Stringcontent=messagemap.get ("content");//Get message content

Stringmsgcontentstring=fromname+ "said:" +content;//constructs a message sent

Send out the content

Charbuffertomsg=charbuffer.wrap (Msgcontentstring.tochararray);

Charbufferfrommsg=charbuffer.wrap (Msgcontentstring.tochararray);

Outfrombound.writetextmessage (FROMMSG);

Outbound.writetextmessage (tomsg);//

Outfrombound.flush;

Outbound.flush;

}

}

@Override

Protectedvoidonclose (intstatus) {

InitServlet.getSocketList.remove (this);

Super.onclose (status);

}

@Override

Protectedvoidonopen (Wsoutboundoutbound) {

Super.onopen (outbound);

Logged in user Register in

if (name!=null) {

InitServlet.getSocketList.put (name,this);//store customer service ID and user

}

}

@Override

publicintgetreadtimeout{

Return0;

}

}

Process the information sent by the foreground in ontextmessage and encapsulate the message to the target

There's another messageutil.

PackageUtil;

Importjava.nio.CharBuffer;

Importjava.util.HashMap;

publicclassmessageutil{

Publicstatichashmap<string,string>getmessage (charbuffermsg) {

hashmap<string,string>map=newhashmap<string,string>;

stringmsgstring=msg.tostring;

Stringm=msgstring.split (",");

Map.put ("FromName", m[0]);

Map.put ("ToName", m[1]);

Map.put ("Content", m[2]);

Returnmap;

}

}

Of course, the front desk must also transmit information in accordance with the prescribed format.

<% @pagelanguage = "java" contenttype= "Text/html;charset=utf-8"

pageencoding= "UTF-8"%>

<! Doctypehtml>

<metahttp-equiv= "Content-type" content= "Text/html;charset=utf-8" >

<title>Index</title>

<scripttype= "Text/javascript" src= "Js/jquery-1.7.2.min.js" ></script>

<%session.setattribute ("User", "small");%>

<scripttype= "Text/javascript" >

Varws=null;

functionstartwebsocket{

if (' WebSocket ' Inwindow)

Ws=newwebsocket ("ws://localhost:8080/websocketuser/websocket.do");

ElseIf (' Mozwebsocket ' Inwindow)

Ws=newmozwebsocket ("ws://localhost:8080/websocketuser/websocket.do");

Else

Alert ("Notsupport");

Ws.onmessage=function (evt) {

alert (evt.data);

Console.log (EVT);

$ ("#xiaoxi"). Val (Evt.data);

Setmessageinnerhtml (Evt.data);

};

Functionsetmessageinnerhtml (InnerHTML) {

document.getElementById (' message '). innerhtml+=innerhtml+ ' <br/> ';

}

Ws.onclose=function (evt) {

Alert ("Close");

document.getElementById (' Denglu '). innerhtml= "Offline";

};

Ws.onopen=function (evt) {

Alert ("Open");

document.getElementById (' Denglu '). innerhtml= "Online";

document.getElementById (' UserName '). innerhtml= ' small ';

};

}

functionsendmsg{

Varfromname= "small";

Vartoname=document.getelementbyid (' name '). Who is value;//sent to?

Varcontent=document.getelementbyid (' writemsg '). value;//Send Content

Ws.send (fromname+ "," +toname+ "," +content ");//Note format

}

</script>

<bodyonload= "Startwebsocket;" >

<p> Chat Feature Implementation </p>

Login Status:

<spanid= "Denglu" > Logging in </span>

<br>

Login Person:

<spanid= "UserName" ></span>

<br>

<br>

<br>

Sent to: <inputtype= "text" id= "name" value= "Xiao Ming" ></input>

<br>

Send content: <inputtype= "text" id= "writemsg" ></input>

<br>

Chat box: <divid= "Message" ></div>

<br>

<inputtype= "button" value= "Send" onclick= "sendmsg" ></input>

</body>

This is the a.jsp page, b ibid.

Through the above code, you can achieve a point-to-point chat function, if done large, can be made into a web version of the chat system, including chat rooms and single-person chat, said WebSocket does not support binary transmission. The above is the whole content of this article, I hope that everyone's learning has helped, but also hope that we support a lot.

HTML5 WebSocket Example code for Point-to-point chat

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.