Home > Web Front-end > JS Tutorial > IM implementation of WebSocketSharp

IM implementation of WebSocketSharp

php中世界最好的语言
Release: 2018-03-16 10:34:38
Original
2838 people have browsed it

This time I will bring you the IM implementation of WebSocketSharp. What are the IM implementations of WebSocketSharp? websocket-sharp is a C# implementation of websocket, supporting .net 3.5 and above to develop server or client. This article mainly introduces the use of websocket-sharp as the server and

JavaScript

as the client to implement a simple IM. WebSocketBehavior

WebSocketBehavior is the core object, which contains four methods: OnOpen, OnMessage, OnClose, OnError and a Sessions object. Anyone who is familiar with websocket knows that the first four methods are used to handle client connections,

sending messages

, connection closing, and errors. Sessions are used to manage all callback connections. Every time a connection is generated, there will be a new Id, and an IWebSocketSession object will be added to sessions. OnClose will be triggered when the page is closed or refreshed, and then the corresponding IwebSocketSession object will be removed from the sessions.

WebSocketSessionManager has a broadcast method: Sessions.Broadcast, which notifies all connected clients. The Send in WebSocketBehavior is equivalent to a single send, and the message can only be sent to one client connected at the moment. After figuring out the above, we can make a simple IM.

Websoket.Server

Create a C# console program. Now add websocket-sharp in Nugget. Already JSON.

Then add a Chat class and inherit WebSocketBehavior. Chat is equivalent to a websocket service. You can create multiple instances of websocketBehavior and then mount them on the websocketServer.

 public class Chat : WebSocketBehavior
    {        private  Dictionary<string,string> nameList=new Dictionary<string, string>();        protected override async Task OnMessage(MessageEventArgs e)
        {
            StreamReader reader = new StreamReader(e.Data);            string text = reader.ReadToEnd();            try
            {                var obj = Json.JsonParser.Deserialize<JsonDto>(text);
                Console.WriteLine("收到消息:" + obj.content + " 类型:" + obj.type + " id:" + Id);                switch (obj.type)
                {                    //正常聊天
                    case "1":
                        obj.name = nameList[Id];                        await Sessions.Broadcast(Json.JsonParser.Serialize(obj));                        break;                    //修改名称
                    case "2":
                        Console.WriteLine("{0}修改名称{1}",nameList[Id],obj.content);
                        Broadcast(string.Format("{0}修改名称{1}", nameList[Id], obj.content),"3");
                        nameList[Id] = obj.content;                        break;                    default:                        await Sessions.Broadcast(text);                        break;
                }
            }            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }          
            //await Send(text);        }        protected override async Task OnClose(CloseEventArgs e)
        {
            Console.WriteLine("连接关闭" + Id);
            Broadcast(string.Format("{0}下线,共有{1}人在线", nameList[Id], Sessions.Count), "3");
            nameList.Remove(Id);
        }        protected override async Task OnError(WebSocketSharp.ErrorEventArgs e) 
        {            var el = e;
        }        protected override async Task OnOpen()
        {
            Console.WriteLine("建立连接"+Id);
            nameList.Add(Id,"游客"+Sessions.Count);
            Broadcast(string.Format("{0}上线了,共有{1}人在线", nameList[Id],Sessions.Count), "3");
        }        private void Broadcast(string msg, string type = "1")
        {            var data= new  JsonDto(){content = msg,type = type,name = nameList[Id]};
            Sessions.Broadcast(Json.JsonParser.Serialize(data));
        }
    }
Copy after login

JsonDto

##

    class JsonDto
    {        public string content { get; set; }        public string type { get; set; }        public string name { get; set; }
    }
Copy after login
View CodeNameList is used here to manage the correspondence between all link IDs and user names. , new online users are all visitors by default. Then three message types are defined in OnMessage. 1 means normal chat, 2 means change the name. 3 indicates system notification. Used to allow the front end to make some interface distinctions.

Then start WebSocketServer in Program. Port 8080 is specified below.

  public class Program
    {        public static void Main(string[] args)
        {            var wssv = new WebSocketServer(null,8080);
            wssv.AddWebSocketService<Chat>("/Chat");
            wssv.Start();
            Console.ReadKey(true);
            wssv.Stop();
        }
    }
Copy after login
Client

html:

 <p id="messages">
    </p>
   <input type="text" id="content" value=""/>
   <button id="sendbt">发送</button>
   <p>昵称:<input type="text" id="nickName"  /> <button id="changebt">修改</button> </p>
Copy after login
View Codejs:

 function initWS() {        ws = new WebSocket("ws://127.0.0.1:8080/Chat");
        ws.onopen = function (e) {
            console.log("Openened connection to websocket");
            console.log(e);
        };
        ws.onclose = function () {
            console.log("Close connection to websocket");            // 断线重连            initWS();
        }
        ws.onmessage = function (e) {
            console.log("收到",e.data)            var p=$("<p>");            var data=JSON.parse(e.data);            switch(data.type){                case "1":
             p.html(data.name+":"+data.content);            break;                case "2":
                p.addClass("gray");
                p.html("修改名称"+data.content)                break;                case "3":
                p.addClass("gray");
                p.html(data.content)                break;
            }
            $("#messages").append(p);
        }
    }
    
    initWS();    function sendMsg(msg,type){
        ws.send(JSON.stringify({content:msg,type:type}));
    }
    $("#sendbt").click(function(){       var text=$("#content").val();
       sendMsg(text,"1")
       $("#content").val("");
    })
    $("#changebt").click(function(){        var text=$("#nickName").val();
        sendMsg(text,"2")
    })
Copy after login
Operating effect:

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to make js pause execution


jquery makes a scoring system

The above is the detailed content of IM implementation of WebSocketSharp. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template