WebSocket realize simple chat room

Source: Internet
Author: User
Tags sendmsg sessions visibility

Front page:

Package com.uptop.websocket;
Import Com.alibaba.fastjson.JSON;

Import Com.uptop.entity.ResultVo;
Import javax.websocket.*;
Import Javax.websocket.server.ServerEndpoint;
Import java.io.IOException;

Import Java.util.concurrent.CopyOnWriteArraySet; /** * WebSocket Chat Room * * @author Administrator * @create 2018-02-05 15:17/@ServerEndpoint ("/wschat") public class W Ebsocketchat {//static variable, used to record the current number of online connections.
    It should be designed to be thread-safe.

    private static int onlinecount = 0; The thread-safe set of the concurrent package, which holds the corresponding Mywebsocket object for each client. To enable the server to communicate with a single client, you can use a map to store where key can be the user identity public static copyonwritearrayset<websocketchat> Websocketset = new C

    Opyonwritearrayset<websocketchat> ();

    A connection session with a client, which needs to be sent to the client to send the data private sessions; /** * Connection to establish a successful call method * * @param session Optional parameters. Session for a connection with a client, you need to send the data to the client/@OnOpen public void OnOpen {this.session = SE
        Ssion;     Websocketset.add (this); Add Addonlinecou in SetNT ();
        Online number plus 1//Send online number of people data resultvo Resultvo = new Resultvo ("0", This.onlinecount, "from server");
        Sendmsg (json.tojsonstring (Resultvo)); SYSTEM.OUT.PRINTLN ("There are new joins.")
    Current online number is "+ Getonlinecount ()");  /** * Connection Shutdown method of call/@OnClose public void OnClose () {websocketset.remove (this);           Deletes the Subonlinecount () from the set;
        Online number minus 1//Send online number of data resultvo Resultvo = new Resultvo ("0", This.onlinecount, "from server");
        Sendmsg (json.tojsonstring (Resultvo)); System.out.println ("There is a connection closed.")
    Current online number is "+ Getonlinecount ()"); 
    /** * The method called after receiving client messages * * @param message Client Sent messages * @param session Optional Parameters * * @OnMessage
        public void OnMessage (String messages, session sessions) {SYSTEM.OUT.PRINTLN ("Message from client: ' +");
        Encapsulates client messages Resultvo Resultvo = new Resultvo ("1", Message, "from client");
      String jsonstr = json.tojsonstring (RESULTVO);  Mass message for (Websocketchat Item:websocketset) {try {item.sendmessage (JSONSTR);
                catch (IOException e) {e.printstacktrace ();
            Continue  /** * * @param session * @param error/@OnError public
        void OnError (Session session, throwable error) {System.out.println ("error occurred");
    Error.printstacktrace (); /** * This method is not the same as the above methods.
     Without annotations, it is based on the method you need to add. * * @param message * @throws IOException */public void SendMessage (String message) throws IOException

    {this.session.getBasicRemote (). SendText (message);
    public static synchronized int Getonlinecount () {return onlinecount;
    public static synchronized void Addonlinecount () {websocketchat.onlinecount++; public static synchronized void Subonlinecount () {Websocketchat.onlinecount--;
                public static void Sendmsg (String msg) {for (websocketchat Item:websocketset) {try {
            Item.sendmessage (msg);
                catch (IOException e) {e.printstacktrace ();
            Continue }
        }
    }
}

Effect Chart:


Note: This case refers to the front page of the IBM Library case and is implemented in the background using Java.


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.