webSocket实现web及时聊天的例子

概述

websocket目前虽然无法普及应用,未来是什么样子,我们不得而知,但现在开始学习应用它,只有好处没有坏处,本随笔的WebSocket是版本13(RFC6455)协议的实现,也是目前websocket的最新协议,协议的英文文档可以查看http://tools.ietf.org/html/rfc6455,中文翻译的文档可以查看http://blog.csdn.net/stoneson/article/details/8063802,下面是聊天的截图例子(很粗糙,但应该不影响)。

客户端的实现

在支持webSocket的浏览器下,调用 new window.WebSocket(url)就返回了websocket对象,此对象有onopen、onmessage、onclose三个常用事件,分别表示连接成功、收到消息、连接断开,发送消息(文件或二进制数据)的方法是send。

           var inc = document.getElementById('incomming');
            var form = document.getElementById('sendForm');
            var input = document.getElementById('sendText');

            inc.innerHTML += "正在连接到服务器 ..<br/>";
            var wsImpl = window.WebSocket || window.MozWebSocket;
            var ws = new wsImpl('ws://localhost:8181/');

            ws.onopen = function () {
                inc.innerHTML += '连接成功<br/>';
            };

            ws.onmessage = function (evt) {
                inc.innerHTML += evt.data + '<br/>';
            };

            ws.onclose = function () {
                inc.innerHTML += '连接已断开<br/>';
            }

            form.addEventListener('submit', function (e) {
                e.preventDefault();
                var val = input.value;
                ws.send(val);
                input.value = "";
            });

服务器的实现

服务器使用NetworkSocket组件的WebSocketServerBase来实现,过程中只要关心业务的实现就可以了,底层的代码,如果你感兴趣,点击链接进去就可以下载和查看。}

    public class Server : WebSocketServerBase
    {
        /// <summary>
        /// 收到文本请求时出发
        /// </summary>
        /// <param name="client">客户端</param>
        /// <param name="text">内容</param>
        protected override void OnText(SocketAsync<Hybi13Packet> client, string text)
        {
            // 回复内容
            this.SendText(client, "->" + text);

            // 转发给其它客户端
            var others = this.AliveClients.Except(new[] { client });
            foreach (var item in others)
            {
                this.SendText(item, client.ToString() + "->" + text);
            }

            // ping此客户端,记录ping的时间
            client.TagBag.PingTime = DateTime.Now;
            this.SendPing(client, null);
        }

        protected override void OnBinary(SocketAsync<Hybi13Packet> client, byte[] bytes)
        {
            this.SendBinary(client, bytes);
        }

        // ping回复
        protected override void OnPong(SocketAsync<Hybi13Packet> client, byte[] bytes)
        {
            var timeSpan = DateTime.Now.Subtract((DateTime)client.TagBag.PingTime);
            Console.WriteLine("ping {0} 用时:{1}ms", client, timeSpan.TotalMilliseconds);
        }

        protected override bool CheckHandshake(SocketAsync<Hybi13Packet> client, HandshakeRequest request)
        {
            Console.WriteLine("{0}进行握手完成", client);
            return base.CheckHandshake(client, request);
        }

        protected override void OnConnect(SocketAsync<Hybi13Packet> client)
        {
            Console.WriteLine("客户连接进来,当前连接数:{0}", this.AliveClients.Count);
        }

        protected override void OnDisconnect(SocketAsync<Hybi13Packet> client)
        {
            Console.WriteLine("{0}断开连接,当前连接数:{1}", client, this.AliveClients.Count);
        }
    }

下载源码

所有相关代码

原文地址:https://www.cnblogs.com/kewei/p/3600128.html