C# WebSocket

2021-03-27 14:26

阅读:538

标签:scroll   字节   connect   private   rev   字节流   one   fork   exce   

WebSocket 协议用于完全双工的双向通信。这种通信,一般在浏览器和Web服务器之间进行,但仅交流那些支持使用WebSocket协议的客户端信息。WebSocket维持一个打开的连接。
Tcp发送是字节流,而WebSocket是在服务器和客户端之间来回发送信息。
HTTP协议做不到服务器主动向客户端推送消息,为此,HTTP使用是,长轮询。
https://www.pubnub.com/blog/2014-12-01-http-long-polling/    
WebSocket 特点:

(1)建立在 TCP 协议之上,服务器端的实现比较容易。

(2)与 HTTP 协议有着良好的兼容性。默认端口也是80和443,并且握手阶段采用 HTTP 协议,因此握手时不容易屏蔽,能通过各种 HTTP 代理服务器。

(3)数据格式比较轻量,性能开销小,通信高效。

(4)可以发送文本,也可以发送二进制数据。

(5)没有同源限制,客户端可以与任意服务器通信。

(6)协议标识符是ws(如果加密,则为wss),服务器网址就是 URL。

来源: http://www.ruanyifeng.com/blog/2017/05/websocket.html

.Net 4.5及以后的版本才提供对websocket的支持,若项目所基于的.Net版本低于.Net 4.5且高于.Net 3.5,不妨尝试采用开源库websocket-sharp。

GitHub路径如下:https://github.com/sta/websocket-sharp    和 https://github.com/statianzo/Fleck

下面引用到  Fleck  和   WebSocketSharpFork

客户端

    /// 
    /// 客户端帮助类  作者:韩永健
    /// 
    public class WebSocketClientHelper
    {
        public delegate void ActionEventHandler();
        public delegate void MessageEventHandler(string message);
        public delegate void ErrorEventHandler(Exception ex);
        /// 
        /// 客户端打开连接时调用
        /// 
        public event ActionEventHandler OnOpen;
        /// 
        /// 客户端关闭连接时调用
        /// 
        public event ActionEventHandler OnClose;
        /// 
        /// 收到客户端信息时调用
        /// 
        public event MessageEventHandler OnMessage;
        /// 
        /// 执行错误时调用
        /// 
        public event ErrorEventHandler OnError;
        /// 
        /// 服务
        /// 
        private WebSocket client;
        /// 
        /// 服务URL
        /// 
        public string ServerUtl { private set; get; }
        /// 
        /// 是否重连
        /// 
        public bool IsReConnection { set; get; }
        /// 
        /// 重连间隔(毫秒)
        /// 
        public int ReConnectionTime { set; get; }
?
        public WebSocketClientHelper(string serverUtl)
        {
            this.ServerUtl = serverUtl;
            client = new WebSocket(this.ServerUtl);
            client.OnOpen += new EventHandler(client_OnOpen);
            client.OnClose += new EventHandler(client_OnClose);
            client.OnMessage += new EventHandler(client_OnMessage);
            client.OnError += new EventHandler(client_OnError);
        }
?
        public WebSocketClientHelper(string serverUtl, bool isReConnection, int reConnectionTime = 1000)
            : this(serverUtl)
        {
            this.IsReConnection = isReConnection;
            this.ReConnectionTime = reConnectionTime;
        }
?
        public void client_OnOpen(object sender, EventArgs e)
        {
            try
            {
                Console.WriteLine("Open!");
                if (OnOpen != null)
                    OnOpen();
            }
            catch (Exception ex)
            {
                //记录日志
                if (OnError != null)
                    OnError(ex);
                else
                    throw ex;
            }
        }
?
        public void client_OnClose(object sender, CloseEventArgs e)
        {
            try
            {
                Console.WriteLine("Close!");
                if (OnClose != null)
                    OnClose();
                //掉线重连
                if (IsReConnection)
                {
                    Thread.Sleep(ReConnectionTime);
                    Start();
                }
            }
            catch (Exception ex)
            {
                //记录日志
                if (OnError != null)
                    OnError(ex);
                else
                    throw ex;
            }
        }
?
        public void client_OnMessage(object sender, MessageEventArgs e)
        {
            try
            {
                Console.WriteLine("socket收到信息:" + e.Data);
                if (OnMessage != null)
                    OnMessage(e.Data);
            }
            catch (Exception ex)
            {
                //记录日志
                if (OnError != null)
                    OnError(ex);
                //else
                //    throw ex;
            }
        }
?
        public void client_OnError(object sender, ErrorEventArgs e)
        {
            if (OnError != null)
                OnError(e.Exception);
            //记录日志
            //掉线重连
            if (IsReConnection)
            {
                Thread.Sleep(ReConnectionTime);
                Start();
            }
        }
        /// 
        /// 启动服务
        /// 
        public void Start()
        {
            try
            {
                client.ConnectAsync();
            }
            catch (Exception ex)
            {
                //日志
                if (OnError != null)
                    OnError(ex);
                else
                    throw ex;
            }
        }
        /// 
        /// 关闭服务
        /// 
        public void Close()
        {
            try
            {
                IsReConnection = false;
                client.CloseAsync();
            }
            catch (Exception ex)
            {
                //记录日志
                if (OnError != null)
                    OnError(ex);
                else
                    throw ex;
            }
        }
        /// 
        /// 发送信息
        /// 
        public void Send(string message)
        {
            try
            {
                client.Send(message);
            }
            catch (Exception ex)
            {
                //记录日志
                if (OnError != null)
                    OnError(ex);
                else
                    throw ex;
            }
        }
        /// 
        /// 发送信息
        /// 
        public void Send(byte[] message)
        {
            try
            {
                client.Send(message);
            }
            catch (Exception ex)
            {
                //记录日志
                if (OnError != null)
                    OnError(ex);
                else
                    throw ex;
            }
        }
    }

  

服务端帮助类
 
    /// 
    /// WebSocket服务辅助类   作者韩永健
    /// 
    public class WebSocketServerHelper
    {
        /// 
        /// 客户端信息
        /// 
        public class ClientData
        {
            /// 
            /// IP
            /// 
            public string IP { get; set; }
            /// 
            /// 端口号
            /// 
            public int Port { get; set; }
        }
        public delegate void ActionEventHandler(string ip, int port);
        public delegate void MessageEventHandler(string ip, int port, string message);
        public delegate void BinaryEventHandler(string ip, int port, byte[] message);
        public delegate void ErrorEventHandler(string ip, int port, Exception ex);
        /// 
        /// 客户端打开连接时调用
        /// 
        public event ActionEventHandler OnOpen;
        /// 
        /// 客户端关闭连接时调用
        /// 
        public event ActionEventHandler OnClose;
        /// 
        /// 收到客户端信息时调用
        /// 
        public event MessageEventHandler OnMessage;
        /// 
        /// 收到客户端信息时调用
        /// 
        public event BinaryEventHandler OnBinary;
        /// 
        /// 执行错误时调用
        /// 
        public event ErrorEventHandler OnError;
        /// 
        /// 服务
        /// 
        private Fleck.WebSocketServer server;
        /// 
        /// socket列表
        /// 
        private Dictionarystring, IWebSocketConnection> socketList = new Dictionarystring, IWebSocketConnection>();
        private List clientList = new List();
        /// 
        /// 客户端ip列表
        /// 
        public List ClientList
        {
            get
            {
                return clientList;
            }
        }
        /// 
        /// 服务URL
        /// 
        public string ServerUtl { private set; get; }
?
        public WebSocketServerHelper(string serverUtl)
        {
            this.ServerUtl = serverUtl;
            server = new Fleck.WebSocketServer(this.ServerUtl);
        }
        /// 
        /// 启动服务
        /// 
        public void Start()
        {
            server.Start(socket =>
            {
                try
                {
                    socket.OnOpen = () => SocketOpen(socket.ConnectionInfo.ClientIpAddress, socket.ConnectionInfo.ClientPort);
                    socket.OnClose = () => SocketClose(socket.ConnectionInfo.ClientIpAddress, socket.ConnectionInfo.ClientPort);
                    socket.OnMessage = message => SocketMessage(socket.ConnectionInfo.ClientIpAddress, socket.ConnectionInfo.ClientPort, message);
                    socket.OnBinary = message => SocketBinary(socket.ConnectionInfo.ClientIpAddress, socket.ConnectionInfo.ClientPort, message);
                    socket.OnError = ex => SocketError(socket.ConnectionInfo.ClientIpAddress, socket.ConnectionInfo.ClientPort, ex);
                    socketList.Add(socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort, socket);
                    ClientList.Add(new ClientData() { IP = socket.ConnectionInfo.ClientIpAddress, Port = socket.ConnectionInfo.ClientPort });
                }
                catch (Exception ex)
                {
                }
            });
        }
?
        /// 
        /// Socket错误
        /// 
        private void SocketError(string ip, int port, Exception ex)
        {
            Console.WriteLine("Error!" + ip + ":" + port + " " + ex);
            socketList.Remove(ip + ":" + port);
            ClientList.RemoveAll(m => m.IP == ip && m.Port == port);
            if (OnError != null)
                OnError(ip, port, ex);
            //else
            //    throw ex;
        }
?
        /// 
        /// Socket打开连接
        /// 
        private void SocketOpen(string ip, int port)
        {
            try
            {
                Console.WriteLine("Open!" + ip + ":" + port);
                if (OnOpen != null)
                    OnOpen(ip, port);
            }
            catch (Exception ex)
            {
                if (OnError != null)
                    OnError(ip, port, ex);
                else
                    throw ex;
            }
        }
?
        /// 
        /// Socket关闭连接
        /// 
        private void SocketClose(string ip, int port)
        {
            try
            {
                Console.WriteLine("Close!" + ip + ":" + port);
                socketList.Remove(ip + ":" + port);
                ClientList.RemoveAll(m => m.IP == ip && m.Port == port);
                if (OnClose != null)
                    OnClose(ip, port);
            }
            catch (Exception ex)
            {
                if (OnError != null)
                    OnError(ip, port, ex);
                else
                    throw ex;
            }
        }
        /// 
        /// 接收到的信息
        /// 
        private void SocketBinary(string ip, int port, byte[] message)
        {
            try
            {
                Console.WriteLine("socket收到信息:byte[]");
                if (OnBinary != null)
                    OnBinary(ip, port, message);
            }
            catch (Exception ex)
            {
                if (OnError != null)
                    OnError(ip, port, ex);
                else
                    throw ex;
            }
        }
        /// 
        /// 接收到的信息
        /// 
        private void SocketMessage(string ip, int port, string message)
        {
            try
            {
                Console.WriteLine("socket收到信息:" + message + " " + ip + ":" + port);
                if (OnMessage != null)
                    OnMessage(ip, port, message);
            }
            catch (Exception ex)
            {
                if (OnError != null)
                    OnError(ip, port, ex);
                else
                    throw ex;
            }
        }
        /// 
        /// 发送信息(单客户端)
        /// 
        public void Send(string ip, int port, string message)
        {
            try
            {
                socketList[ip + ":" + port].Send(message);
            }
            catch (Exception ex)
            {
                if (OnError != null)
                    OnError(ip, port, ex);
                else
                    throw ex;
            }
        }
        /// 
        /// 发送信息(单客户端)
        /// 
        public void Send(string ip, int port, byte[] message)
        {
            try
            {
                socketList[ip + ":" + port].Send(message);
            }
            catch (Exception ex)
            {
                if (OnError != null)
                    OnError(ip, port, ex);
                else
                    throw ex;
            }
        }
        /// 
        /// 发送信息(所有客户端)
        /// 
        public void SendAll(string message)
        {
            for (int i = 0; i )
            {
                var item = socketList.ElementAt(i);
                try
                {
                    item.Value.Send(message);
                }
                catch (Exception ex)
                {
                    if (OnError != null)
                        OnError(item.Value.ConnectionInfo.ClientIpAddress, item.Value.ConnectionInfo.ClientPort, ex);
                    else
                        throw ex;
                }
            }
        }
        /// 
        /// 发送信息(所有客户端)
        /// 
        public void SendAll(byte[] message)
        {
            for (int i = 0; i )
            {
                var item = socketList.ElementAt(i);
                try
                {
                    item.Value.Send(message);
                }
                catch (Exception ex)
                {
                    if (OnError != null)
                        OnError(item.Value.ConnectionInfo.ClientIpAddress, item.Value.ConnectionInfo.ClientPort, ex);
                    else
                        throw ex;
                }
            }
        }
    }

 

C# WebSocket

标签:scroll   字节   connect   private   rev   字节流   one   fork   exce   

原文地址:https://www.cnblogs.com/nanguoyezi/p/9351555.html


评论


亲,登录后才可以留言!