C#编程之C# WebSocket
小标 2018-11-14 来源 : 阅读 1098 评论 0

摘要:本文主要向大家介绍了C#编程之C# WebSocket,通过具体的内容向大家展示,希望对大家学习C#编程有所帮助。

本文主要向大家介绍了C#编程之C# WebSocket,通过具体的内容向大家展示,希望对大家学习C#编程有所帮助。

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。
来源: //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 Dictionary socketList = new Dictionary();
        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 < socketList.Count; 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 < socketList.Count; 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#.NET频道!

本文由 @小标 发布于职坐标。未经许可,禁止转载。
喜欢 | 0 不喜欢 | 0
看完这篇文章有何感觉?已经有0人表态,0%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程