WebSocket implements a simple web chat room __web

Source: Internet
Author: User
Tags xmlns tomcat
1. Requires Tomcat7.0 so server 2. JDK7.0 3. Manually add the Tomcat7.0 in the Lib directory of three packets Catalina.jar, Tomcat-coyote.jar, Websocket-api.jar 4. After the project is deployed, delete 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=reques         T.getsession ();     return new Mymessageinbound (); }
Private class Mymessageinbound extends Messageinbound {wsoutbound myoutbound;
/** * When the 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 Client Outbound.writetextmessage (Charbuffer.wrap ("hello!"))             ;             } catch (IOException e) {e.printstacktrace (); }         }
/** * When the user exits, the WebSocket shutdown event, the parameter status should come from a few constants defined in Org.apache.catalina.websocket.Constants *, you can refer to the documentation or check the tomcat source */ @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 IO Exception {for (Mymessageinbound mmib:userlist) {//loop sends the current user's information to all online users charbuffer buffer = Cha                 Rbuffer.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 Voi d onbinarymessage (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> WebSocket handshake Complete, connection successful callback//There is a question, supposedly new websocket will start to connect, if the connection before the setting OnOpen successful, will also trigger this callback Ws.onopen = function () {// Request succeeded};
Receives a text message sent by the server, Event.data represents the text content ws.onmessage = function (message) {document.getElementById ("Talkinfo"). innerhtml+= message.data+ "Turn off WebSocket Callback ws.onclose = function () {//alert (' closed! ');};
By websocket you want to send a text message to the server function Posttoserver () {Ws.send (document.getElementById ("content"). Value); document.getElementById ("Content"). Value = "";}
Close WebSocket function 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>

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.