WebSocket implement a simple web chat room

Source: Internet
Author: User

1. Requires Tomcat7.0 so the server2. Need JDK7.03. Manually join Tomcat7.0 in the Lib directory under the three pack Catalina.jar, Tomcat-coyote.jar, WEBSOCKET-API.JAR4. After the project is deployed, remove the Catalina.jar, Tomcat-coyote.jar, Websocket-api.jar three packages under the current project in the server. 5. The project directory structure is as follows



Servlet code
Package com.yc.websockets;
Import Java.io.ioexception;import java.nio.bytebuffer;import Java.nio.charbuffer;import Java.util.ArrayList;import Java.util.List;
Import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpsession;import Javax.websocket.OnClose ; Import Javax.websocket.onmessage;import Javax.websocket.onopen;import Javax.websocket.session;import Javax.websocket.server.ServerEndpoint;
Import Org.apache.catalina.websocket.messageinbound;import Org.apache.catalina.websocket.streaminbound;import Org.apache.catalina.websocket.websocketservlet;import Org.apache.catalina.websocket.WsOutbound;
@SuppressWarnings ({"Deprecation", "unused", "serial"}) public class Websockettest extends Websocketservlet {private static list<mymessageinbound> userlist = new arraylist<mymessageinbound> ();Private HttpSession session;
@Override protected Streaminbound createwebsocketinbound (String str, httpservletrequest request) {Session=request.getsession ();    return new Mymessageinbound (); }
Private class Mymessageinbound extends Messageinbound {wsoutbound myoutbound;
/** * When a user logs in, the WebSocket handshake is complete, created, Wsoutbound used to send data to the client */public void OnOpen (Wsoutbound outbound) {try {System.out.println ("Open Client.");                This.myoutbound = outbound; Userlist.add (this);            Add current user//Send message to Customer Outbound.writetextmessage (Charbuffer.wrap ("hello!"));            } catch (IOException e) {e.printstacktrace (); }        }
/*** When user exits, WebSocket Shutdown event, parameter status should be from Org.apache.catalina.websocket.Constants* Several constants defined in the, can refer to the document or check the Tomcat source code*/@Override public void OnClose (Int. status) {Userlist.remove (this);//Remove Current user}
/** * Accept the message sent by the user, there is text message data arrives */@Override public void Ontextmessage (Charbuffer cb) throws Ioexce ption {for (Mymessageinbound mmib:userlist) {//loop sends the current user's information to all online users charbuffer buffer = Charbuffe                R.wrap (CB); Mmib.myoutbound.writeTextMessage (buffer); Invokes the sending method of the specified user to send the current user information mmib.myoutbound.flush (); Empty Cache}}
/** * has binary message data arrives, temporarily did not study this function under what circumstances trigger, JS WebSocket supposedly should only send text information only to */@Override public void on Binarymessage (Bytebuffer bb) throws IOException {}}}

Web. XML configuration File
 <?xml version= "1.0" encoding= "UTF-8"?><web-app version= "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 "><display-name></display-name><servlet><servlet-name>webServlet</servlet-name><servlet-class>com.yc.websockets.WebSocketTest</servlet-class></servlet><servlet-mapping><servlet-name>webServlet</servlet-name><url-pattern>/webServlet</url-pattern></servlet-mapping><welcome-file-list><welcome-file>index.html</welcome-file></welcome-file-list></web-app>
index.html
<! DOCTYPE Html>Set WebSocket, note that the protocol is WS, the request is pointing to the corresponding Websocketservlet/* Set WebSocket, note that the protocol is WS, the request is pointing to the corresponding Websocketservletvar url = "Ws://127.0.0.1:8080/j2ee6/echo.ws";Create WebSocket instance, the following mozwebsocket is the implementation of Firefoxif (' WebSocket ' in window) {WS = new WebSocket (URL);} else if (' mozwebsocket ' in window) {WS = new Mozwebsocket (URL);} else {Alert (' Unsupported. ');Return}*/var ws = new WebSocket ("Ws://218.196.14.208:8080/websocket/webservlet");
WebSocket handshake completed, connection successful callbackThere is a doubt that the new websocket will start to connect, if the connection is successful before setting OnOpen, will trigger this callbackWs.onopen = function () {Request succeeded};
Receive the text message sent by the server, Event.data represents the text contentWs.onmessage = function (message) {document.getElementById ("Talkinfo"). innerhtml+=message.data+ "};
Turn off callback for WebSocketWs.onclose = function () {Alert (' closed! ');};
Send a text message to the server by WebSocketfunction Posttoserver () {Ws.send (document.getElementById ("content"). Value);document.getElementById ("Content"). Value = "";}
Close WebSocketfunction Closeconnect () {Ws.close ();}</script><style>* {margin:0 Auto;padding:0px;font-size:12px;Font-family: "Microsoft Jas Black";line-height:26px;}
#bigbox {margin:0px Auto;padding:0px;width:70%;}
#talkInfo {width:100%;height:500px;border:1px solid red;Overflow:scorll;}
#operation {width:100%;height:30px;margin-top:10px;}
#content {height:30px;line-height:30px;} </style><div id= "BigBox" ><div id= "Talkinfo" ></div><div id= "Operation" ><center><input type= "text" name= "content" id= "content" size= "/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp" ;<input type= "button" value= "&nbsp; send &nbsp; "Onclick=" Posttoserver () "/>&nbsp;&nbsp;<input type= "button" value= "&nbsp; my flash &nbsp; "Onclick=" Closeconnect () "/></center></div></div></body> 

WebSocket implement a simple web chat room

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.