Implementing a Web chat room using WebSocket

Source: Internet
Author: User
Tags cdata apache tomcat

Know WebSocket for a long time, but has not mentioned interest to understand it.

Listen to the mature caterpillar today speaking of slack. A little trial, found that slack chat function is quite powerful, looked at the network request, the discovery is based on WebSocket implementation. Immediately mention the interest, want to know the next strong WebSocket.

First understand the next WebSocket.

    • Introduction to open source China: Http://www.oschina.net/p/websocket
    • introduction of Baidu Encyclopedia:http://baike.baidu.com/link?url=yMTBVobtkp1E1a0wrRJlnEXzREuPQFF3psqG6wKJsSxY0_ qvpkdepz5ayxqfn6tbfdyrre3agyak9hebf6279k

There are few examples of WebSocket on the Internet, but the best examples are already there. In the occasional discovery of Tomcat's own example, there is a chat room example based on the WebSocket implementation. Here is not caught dead, directly to use.

First, the service-side implementation Chatannotation.java

/* * Licensed to the Apache software Foundation (ASF) under one or more * Contributor license agreements. See the NOTICE file distributed with * This work for additional information regarding copyright ownership. * The ASF licenses this file to you under the Apache License, Version 2.0 * (the "License");  You are not a use of this file except in compliance with * the License. Obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * unless required by applic  Able law or agreed into writing, software * Distributed under the License is distributed on a "as is" BASIS, * without Warranties or CONDITIONS of any KIND, either express OR implied. * See the License for the specific language governing permissions and * limitations under the License. */package Websocket.chat;import Java.io.ioexception;import Java.util.set;import Java.util.concurrent.copyonwritearrayset;import Java.util.concurrent.atomic.atomicinteger;import Javax.websocket.onclose;impORT Javax.websocket.onerror;import Javax.websocket.onmessage;import Javax.websocket.onopen;import Javax.websocket.session;import javax.websocket.server.ServerEndpoint; @ServerEndpoint (value = "/chat") public class    chatannotation {private static final String Guest_prefix = "GUEST";    private static final Atomicinteger Connectionids = new Atomicinteger (0);    Private static final set<chatannotation> connections = new copyonwritearrayset<> ();    Private final String nickname;    Private session session;    Public Chatannotation () {nickname = Guest_prefix + connectionids.getandincrement ();        } @OnOpen public void Start (Session session) {this.session = session;        Connections.add (this);        String message = String.Format ("*%s%s", nickname, "has joined.");    Broadcast (message);        } @OnClose public void End () {connections.remove (this); String message = String.Format ("*%s%s", nickname, "Has disconnected. ");    Broadcast (message); } @OnMessage public void incoming (String message) {//Never trust the client//TODO: Filter input content Broadcas    t (message); } @OnError public void OnError (Throwable t) throws Throwable {System.out.println ("Chat Error:" + t.tostring    ());                } private static void Broadcast (String msg) {for (chatannotation client:connections) {try {                Synchronized (client) {client.session.getBasicRemote (). SendText (msg);                }} catch (IOException e) {System.out.println ("Chat error:failed to send message to client");                Connections.remove (client);                try {client.session.close (); } catch (IOException E1) {//Ignore} String message = String.Format ("*               %s%s ", Client.nickname," has been disconnected. "); Broadcast (message); }        }    }}

Explain the above code a little bit.

    1. The @ServerEndpoint (value = "/websocket/chat") defines a websocket server. Value is the access address. In this example: The client connects via Ws://{domain}/{context}/chat
    2. set<chatannotation> connections used to store connection instances in a chat room
    3. @OnPen, the method that is called when the connection is created
    4. @OnClose, the method that is called when the connection is closed
    5. @OnMessage, the method that is called during the transfer of information
    6. @OnError, the method that is called when an error occurs
    7. Broadcast (String msg), through connections, the method of pushing information to all other users

The implementation of the client chat.xhtml

<?xml version= "1.0" encoding= "UTF-8"?><!--Licensed to the Apache software Foundation (ASF) under one or more C  Ontributor license agreements.  See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License");  You are not a use of this file except in compliance with the License.  Obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 unless required by applicable or agreed to writing, software distributed under the License are distributed on a "as is" BASIS, without warranties  or CONDITIONS of any KIND, either express or implied. See the License for the specific language governing permissions and limitations under the license.--> 

the client's code is also very simple, that is, when loading the page, create a WebSocket connection to the server.

Chat.connect (' ws://' + window.location.host + '/websocket/chat ');

then the message is sent and the message is received.

Once you have completed the above code, you can deploy it. The servlet container I'm using here is Tomcat 8. Here is my configuration:

<context path= "/websocket" docbase= "/users/cevin/documents/workspace/tomcat_websocket_chat/web" reloadable= " True "/>

end of deployment, launch Tomcat, visit: http://localhost:8080/websocket/chat.xhtml, see this page to show that the deployment was successful.

Basically, this example will tell you how to use WebSocket to develop. Such a powerful WebSocket, think of a thought are excited!

Implementing a Web chat room using websocket

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.