WebSocket Web chat room implementation (server side:. NET + Windows services, Front end: HTML5)

Source: Internet
Author: User

WebSocket is a HTML5 in the comparison has a unique piece, it makes the previous in the client software commonly used in the socket in the Web program can also be easily used, a larger increase in efficiency. Don't say much nonsense, go straight to the question.

The web chat room consists of 2 parts, a backend server + front page.
1. Backend Services Section:. net4.0 + Windows Services . The Windows services hosted in the process are more stable and reliable than boarding in IIS (the examples in this article are shown in the Windows console program, followed by the code for the full Windows service).
2, the front-end part:HTML5 + jQuery + bootstrap. Basic front-end rapid development tool.

First, analyze the scene requirements of the chat room in order to build the appropriate data structure.

1, on-line user class Onlineuser The basic characteristics of the user name name (sex age what first ignore), of course, in the system design, the name does not well distinguish between different users, so you need a unique identifier ID. In addition, because there may be more than one chat room, the chat room number Roomid is also one of the characteristics of the user. In conclusion, the structure of the online user class Onlineuser is as follows:

///<summary>///online user information ///<summary>public class onlineuser{public int Id {get; set;} public string Name {get; set; } public string roomid {get; set; } public string SessionId {get; Span class= "Hljs-keyword" >set; }} 
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

Ps:sessionid is an attribute that is subsequently added, which can be ignored first.

2, the message class messages message is the core of the chat room, my simplest message body should contain the following members, message sender Fromuserid, message recipient Touserid, message type type, message contents content , message time.

public class Message{ Span class= "Hljs-keyword" >public int fromuserid {get; set; } public int touserid {get; set; } public int Type {get; set; } public string time {get; set; } public string Content {get; Span class= "Hljs-keyword" >set; }} 
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

PS: Here type is represented by the int type, and is used for subsequent message delivery so that it is wrapped in JSON format. But when judged, it will be converted to MessageType format enumeration type, MessageType tentatively contains the following States,

PublicEnum messagetype{///<summary>New User access///<summary> Newuserin =1,///<summary>User left///<summary> UserExit =2,///<summary>New users to provide their own information///<summary> Reprotuserinfo = 3, ///<summary> ///new text message ///</summary> Newtextmessage = 4, ///<summary> ///broadcast basic information ///</summary> Broadcastbasicinfo = 5}          
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

II. Structure of the project

1, the service side project structure is as follows:

This is a Windows console program, Program.cs is the portal, ChatWebSocket.cs is the core code fast, externally referenced DLLs include the JSON Operation class Library and the socket Operation class Library.  
where the Model folder is the basic data structure mentioned above, here is a look at the core code chatwebsocket. The use of the SuperSocket has been the main operation of the socket is fully encapsulated, using the following methods:

/* listening address (note that The address here must be the same as the front-end JS address!! ) */const string IP =  "127.0.0.1"; Span class= "hljs-comment" >/* listening port */const int port = 2016; /* wsserver = null; /* current online user list */list<onlineuser> oluserlist = new List< Onlineuser> (); /* timed notification client thread */backgroundworker bkwork = null;    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

Here, Websocketserver is the socket server class encapsulated in SuperSocket, Oluserlist is a list of online users, Bkwork is a background thread, responsible for sending some system information to the client regularly.

In the constructor:

public ChatWebSocket(){    /* 初始化 以及 相关事件注册 */    wsServer = new WebSocketServer();    /* 有新会话握手并连接成功 */ wsServer.NewSessionConnected += WsServer_NewSessionConnected; /* 有会话被关闭 可能是服务端关闭 也可能是客户端关闭 */ wsServer.SessionClosed += WsServer_SessionClosed; /* 有新文本消息被接收 */ wsServer.NewMessageReceived += WsServer_NewMessageReceived;}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

Websocketserver has several more important events,
1, Newsessionconnected has a new session handshake and successful connection
2, Sessionclosed has a session is closed may be the server shutdown may also be the client shutdown
3. newmessagereceived a new text message is received
Where the Newmessagereceived event is an important event of message delivery and the event that we focus on, the following is a list of the 3 event's method bodies:

A new session handshake and a successful connectionPrivatevoidWsserver_newsessionconnected (websocketsession session) {Loghelper.write (session). Sessionid.tostring () +"connect!");}A new text message is receivedPrivatevoidWsserver_newmessagereceived (websocketsession session,StringValue) {Loghelper.write ("Receive Message:" +Value);var msg = jsonconvert.deserializeobject<message> (Value); MessageType MT = (MessageType) msg. Type;Switch (MT) {/* Users report their own information, associating the UserID with SessionID */Case MESSAGETYPE.REPROTUSERINFO:OLUSERLIST.ADD (New Onlineuser {SessionId = session. SessionID, Id = Msg. Fromuserid, realname = Msg. Fromusername, Roomid = Msg. Roomid});/* Notify other users */SendMessage (Session,New Message {Fromuserid = Msg. Fromuserid, Fromusername = Msg. Fromusername, Touserid =0,Person of the same room Type = (int) Messagetype.newuserin, Content ="", Time = DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss"), Roomid = Msg. Roomid});Break/* User text (picture) message, server forwarding */Case Messagetype.newtextmessage:/* Notify other users */MSG. Time = DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss"); SendMessage (Session, MSG);BreakDefaultBreak }}There is a session being shut down that may be the server shutdown or the client shutting downprivate void wsserver_sessionclosed (websocketsession session, Closereason value) {Loghelper.write ( Session. Sessionid.tostring () + "exit!"); var u = oluserlist.find (m = = M.sessionid = = Session. SessionID); if (U = = null) { return;} oluserlist.remove (U); //Notify other users SendMessage (session, new Message {Fromuserid = u.id, Fromusername = u.realname, Touserid = 0,
                                                   
                                                    //person in the same room Type = (
                                                    int) messagetype.userexit, Content = "", Roomid = U.roomid});}  
                                                     
      1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • Ten
    • one
    • 2
    • (
    • )
    • +
    • +
    • /
    • 0
    • +
    • all
    • +
    • +
    • +
    • -
    • 29
    • +
    • +
    • all
    • +
    • +
    • PNS
    • up
    • i>39
    • 48
    • all
    • /
    • /
    • /
    • /li>
    • ,
    • ,
    • ,
    • up-
    • -
    • +
    • -
    • +
    • *
    • +
    • ,
    • ,
    • +
    • $
    • "
    • " "
    • "
    • "
    "
      1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • Ten
    • one
    • 2
    • (
    • )
    • +
    • +
    • /
    • 0
    • +
    • all
    • +
    • +
    • +
    • -
    • 29
    • +
    • +
    • all
    • +
    • +
    • PNS
    • up
    • i>39
    • 48
    • all
    • /
    • /
    • /
    • /li>
    • ,
    • ,
    • ,
    • up-
    • -
    • +
    • -
    • +
    • *
    • +
    • ,
    • ,
    • +
    • $
    • "
    • " "
    • "
    • "
    "

Among them, the SendMessage(WebSocketSession session, Message msg) method is as follows:

private void SendMessage (websocketsession session, Message msg) {//-1: The whole; 0: Same room; Left: specific user var users = msg. Touserid = =-1? Oluserlist:msg. Touserid = =0? Oluserlist             
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

In addition, the start and stop of the websocketserver is very simple:

public void Start(){    if (!wsServer.Setup(IP, PORT))    {        throw new Exception("设置WebSocket服务侦听地址失败!"); } if (!wsServer.Start()) { throw new Exception("启动WebSocket服务侦听失败!"); }}public void Stop(){ if (wsServer != null) { wsServer.Stop(); }}

WebSocket Web chat room implementation (server side:. NET + Windows services, Front end: HTML5)

Related Article

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.