WebSocket implements simple web chat rooms and websocketweb chat rooms

Source: Internet
Author: User

WebSocket implements simple web chat rooms and websocketweb chat rooms
1. tomcat is required, so Server 2. JDK7.03. manually add the three packages catalina under the lib directory in Tomcat7.0. jar, tomcat-coyote.jar, websocket-api.jar4. after the project is deployed. jar, tomcat-coyote.jar, websocket-api.jar three packages are deleted. 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 on, the WebSocket handshake is complete and the creation is complete. WsOutbound is 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 the current user // send the outbound message to the client. writeTextMessage (CharBuffer. wrap ("Hello! ");} Catch (IOException e) {e. printStackTrace ();}}
/*** WebSocket Close event when the user exits. The parameter status should be from org. apache. catalina. websocket. several Constants defined in Constants *. You can refer to the document or check the Tomcat source code */@ Override public void onClose (int status) {userList. remove (this); // remove the current user}
/*** The message sent by the user is received, and the text message data reaches */@ Override public void onTextMessage (CharBuffer cb) throws IOException {for (MyMessageInbound mmib: userList) {// cyclically send the current user's information to all online users. CharBuffer buffer = CharBuffer. wrap (cb); mmib. myoutbound. writeTextMessage (buffer); // call the sending method of the specified user to send the current user message mmib. myoutbound. flush (); // clear cache }}
/*** The arrival of binary message data does not work out when this function is triggered, in JavaScript WebSocket, it is reasonable to send only text information to */@ Override public void 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-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 is complete, and the callback is successful. // if you have any questions, the connection starts when new WebSocket is set. If the connection succeeds before onopen is set, will this callback ws be triggered. onopen = function () {// request succeeded };
// Receives the text message sent by the server, event. data indicates the text content ws. onmessage = function (message) {document. getElementById ("talkInfo "). innerHTML + = message. data + "// Disable WebSocket callback ws. onclose = function () {// alert ('closed! ');};
// Use WebSocket to send a text message to the server. function postToServer () {ws. send (document. getElementById ("content "). value); document. getElementById ("content "). value = "";}
// Disable WebSocketfunction closeConnect () {ws. close () ;}</script> <style> * {margin: 0 auto; padding: 0px; font-size: 12px; font-family: ""; 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.