WebSocket 服务端和客户端

  IDictionary<string, IWebSocketConnection> SocketList = new Dictionary<string, IWebSocketConnection>();
 private void startSockeListener()
        {
            WebSocketServer server = new WebSocketServer("ws://0.0.0.0:30007");//监听本机                                                                                 
            
            //出错后进行重启
            server.RestartAfterListenError = true;
            //开始监听
            server.Start(socket =>
            {
                socket.OnOpen = () => //连接建立事件
                {
                    //客户端url
                    string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
                    string clientid = socket.ConnectionInfo.Id.ToString();
                    SocketList.Add(clientid, socket);
                    socket.Send("欢迎加入");
                };
                socket.OnClose = () => //连接关闭事件
                {
                    string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
                    //如果存在这个客户端,那么对这个socket进行移除
                    if (SocketList.ContainsKey(clientUrl))
                    {
                        //if (SocketList[clientUrl] != null)
                        //{
                        // SocketList[clientUrl].Close();
                        //}
                        SocketList.Remove(clientUrl);
                    }
                };
                socket.OnMessage = message => //接受客户端网页消息事件
                {
                    string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
                    Console.WriteLine(DateTime.Now.ToString() + "|服务器:【收到】来客户端网页:" + clientUrl + "的信息:\n" + message);
                    Console.WriteLine(message);
                    SendMessage(socket.ConnectionInfo.Id.ToString(), message + "-->" + DateTime.Now.ToString());
                };
            });
        }
        //向客户端发送消息
        private void SendMessage(string clientid,string msg)
        {
            foreach (var item in SocketList.Values)
            {
                if (item.IsAvailable == true)
                {                    
                    if (item.ConnectionInfo.Id.ToString() == clientid)
                    {
                        item.Send(msg);
                    }
                }
            }

        }
        //关闭与所有客户端的连接
        private void CloseSocket()
        {

            foreach (var item in SocketList.Values)
            {
                if (item != null)
                {
                    item.Close();
                }
            }
        }

  对应客户端HTML代码

 <!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>WebSocket测试</title>
    <style>
        .div1 {
            height: 188px;
            width: 403px;
            border: 1px solid blue;
            margin: auto;
            text-align: center;
        }
        h4
        {
            margin:auto;
             text-align:center;
        }
    </style>
    <script type="text/javascript">
        var host = window.location.host;
        var webSocket = {};
        //创建websockt
        function CreateWebSocket() {
            webSocket = new WebSocket("ws://127.0.0.1:8084");
            webSocket.onopen = WebSokectOnOpen;
            webSocket.onmessage = WebSocketOnMessage;
            webSocket.onclose = WebSocketOnClose;
        };
 
        //建立连接事件
        function WebSokectOnOpen() {
            //alert("已经打开连接!");
            webSocket.Send("WebSocketCreate Success!");
        };
 
        //监听事件
        function WebSocketOnMessage(event) {
            //监听来自客户端的数据
            alert(event.data);
        };
 
        function WebSocketOnClose() {
            //监听来自客户端的数据
            alert('和服务器断开连接');
        };
 
        //发送事件
        function WebSocketSendMsg() {
            //获取text中的值
            var text = document.getElementById("Text1").value;
            //发送到服务器
            webSocket.send(text);
        };
    </script>
</head>
<body onload="CreateWebSocket()">
    <div class="div1">
        <h4>Test</h4>
        <h4>WebSocket</h4>
        <h4> </h4>
        <input type="text" id="Text1" />
        <input type="button" onclick="WebSocketSendMsg()" value="发送数据" />
    </div>
</body>
</html>

  

 

posted @ 2022-09-07 17:19  liaoyi  阅读(141)  评论(0编辑  收藏  举报