WebSocket Introduction and a simple chat room

Source: Internet
Author: User
Tags sendmsg apache tomcat

What is WebSocket?

WebSocket a protocol for full-duplex communication on a single TCP connection. The WebSocket communication protocol was established as standard RFC 6455 by the IETF in 2011 and was supplemented by RFC7936, WEBSOCKETAPI by the network.

WebSocket is a standalone protocol that is created on TCP, and the only association to HTTP is a protocol switch using the HTTP protocol's 101 status Code, which uses a TCP port of 80 and can be used to bypass most firewall restrictions.

WebSocket makes the exchange of data between client and server simpler, allowing the service to push data directly to the client without requiring the client to make a request, and in the WebSocket API, the browser and server only need to complete a handshake, and the two can create a persistent connection directly. and allows data to be transmitted in both directions.

Currently common browsers such as Chrome, IE, Firefox, Safari, Opera and so on support WebSocket, and need the service-side program to support WebSocket.

--------------------------------------------------------------------------------------

The above is from the wiki, in general WebSocket realizes the two-way communication between the server and the browser, get rid of the previous one to answer the communication way, can freely transfer data.

What are the advantages of websocket?
    • Because there is no HTTP header information, the transmitted packets are small
    • Server can proactively push information
WebSocket Handshake Protocol

Or copy the example on the wiki, websocket the browser will make the following request to the server when establishing the connection

get/http/1.1Nullsec-websocket-key:sn9crrp/n9ndmgdcy2vjfq==sec- Websocket-version:13

This request tells the server that it is about to switch to the WebSocket protocol, and if the server supports it, it will return the following information

http/1.1 101 Switching ProtocolsUpgrade:websocketConnection:UpgradeSec-websocket-accept: ffboob7fakllxgrsz0bt3v4hq5s=secNullsec-websocket-location:ws://  example.com/

At this point, the handshake phase is complete and the server and browser can start sending and receiving information

Use WebSocket to implement a simple web chat room
    • Using Tomcat8 's Websocket-api
    • Refer to the example that Tomcat comes with

Server-Side Chatservlet

 PackageCom.yc.chatroom;Importjava.io.IOException;ImportJava.util.Set;ImportJava.util.concurrent.CopyOnWriteArraySet;ImportJava.util.concurrent.atomic.AtomicInteger;ImportJavax.servlet.annotation.WebServlet;ImportJavax.websocket.OnClose;ImportJavax.websocket.OnError;ImportJavax.websocket.OnMessage;ImportJavax.websocket.OnOpen;Importjavax.websocket.Session;Importjavax.websocket.server.ServerEndpoint; @ServerEndpoint (Value= "/websocket/chat")//Specify client Connection address Public classChatservlet {Private Static Final LongSerialversionuid = 1L; Private Static FinalString guest_prefix = "GUEST"; Private Static FinalAtomicinteger Connectionids =NewAtomicinteger (0); Private Static Finalset<chatservlet> connections =NewCopyonwritearrayset<chatservlet>(); Private FinalString Nickname; PrivateSession session;  PublicChatservlet () {Nickname= Guest_prefix +connectionids.getandincrement (); } @OnOpen Public voidStart (Session session) { This. session =session; Connections.add ( This); String message= String.Format ("*%s%s", nickname, "has joined."); Broadcast (message); //Broadcast user Join message} @OnClose Public voidEnd () {Connections.remove ( This); String message= String.Format ("*%s%s", nickname, "Has disconnected."); Broadcast (message); //Broadcast user Launch message} @OnMessage Public voidIncoming (String message) {//never trust the clientString filteredmessage = String.Format ("%s:%s", nickname, Message.tostring ()); Broadcast (filteredmessage); //Broadcast Send content} @OnError Public voidOnError (Throwable t)throwsthrowable {t.printstacktrace (); }  Private Static voidBroadcast (String msg) { for(Chatservlet client:connections) {Try {        synchronized(client) {client.session.getBasicRemote (). SendText (msg);//send a message to everyone        }      } Catch(IOException e) {connections.remove (client); Try{client.session.close (); } Catch(IOException E1) {//Ignore} String Message= String.Format ("*%s%s", Client.nickname, "has been disconnected.");      Broadcast (message); }    }  }}

Browser-side index.jsp

<%@ page contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%>input#chat {width:410px} #console-container {width:400px;}  #console {border:1px solid #CCCCCC; Border-right-color: #999999; Border-bottom-color: #999999;  height:170px; Overflow-Y:scroll;  padding:5px; Width:100%;} #console p {padding:0; Margin:0;}</style>ID= "Chat"/> </p> <div id= "Console-container" > <div id= "Console" ></div> </div&gt  ; </div></body><script type= "Text/javascript" >/*** Specify the WebSocket address to connect to * if you use HTTPS, use wss://**/var socket=NewWebSocket (' ws://' + window.location.host+ '/chatroom/websocket/chat '); //connecting to a serverSocket.onopen =function () {showmsg (' Info:websocket connection opened. '); document.getElementById (' Chat '). onkeydown =function (event) {if(Event.keycode = = 13) {sendmsg ();  }    };  }; //disconnecting from the serverSocket.onclose =function () {document.getElementById (' Chat '). onkeydown =NULL; ShowMsg (' Info:websocket closed. ');  }; //communication with the serverSocket.onmessage =function (message) {showmsg (message.data);  }; //displaying Messagesfunction showmsg (message) {var console= document.getElementById (' console '); var p= document.createelement (' P '); P.style.wordwrap= ' Break-word '; P.innerhtml=message;    Console.appendchild (P);  while(Console.childNodes.length > 25) {console.removechild (console.firstchild); } console.scrolltop=Console.scrollheight; }  //Send Messagefunction sendmsg () {var message= document.getElementById (' chat '). Value; if(Message! = ") {socket.send (message); document.getElementById (' Chat '). Value = '; }  }</script>

Run results

Open two windows at a time, the user is guest0, guest1

GUEST0:

Guest1:

Guest0 exit:

Original link Address: https://mssora.com/websocket-intro-and-chatroom/

WebSocket Introduction and a simple 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.