博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C# Socket通信改进记录
阅读量:7052 次
发布时间:2019-06-28

本文共 2104 字,大约阅读时间需要 7 分钟。

1. Socket

  1. 使用原始Socket,Send和Recv方法 进行发送和消息获取。(另起后台线程 不停获取和发送)
    1.   
      public void RecvMsg()        {            //receive message            bool isListen = true;            while (isListen)            {                string recStr = "";                byte[] recBytes = new byte[4096];                int bytes = clientSocket.Receive(recBytes, recBytes.Length, 0);                recStr += Encoding.UTF8.GetString(recBytes, 0, bytes);                if (!String.IsNullOrWhiteSpace(recStr))                {                    if (recStr.EndsWith(Environment.NewLine))                    {                        recStr = recStr.Substring(0, recStr.Length - Environment.NewLine.Length);                    }                    AppendContet(recStr);                }            }        }

       

  2. 使用Socket BeginSend 和BeginReceive 进行异步发送和消息获取。
    1.   
      private void button1_Click(object sender, EventArgs e)        {            //send message            string sendStr = txtMsg.Text;            byte[] sendBytes = Encoding.UTF8.GetBytes(sendStr);            clientSocket.BeginSend(sendBytes, 0, sendBytes.Length, SocketFlags.None, new AsyncCallback(Send_Complete), clientSocket);        }        private void Send_Complete(IAsyncResult e)        {            if (e.IsCompleted)            {                AppendDebugMsg("异步发送已完成");            }            else            {                AppendDebugMsg("异步发送失败");            }            var socket = e.AsyncState as Socket;            if (socket == null)            {                AppendDebugMsg("发送异步Socket为空");            }        }

       

  3. 使用 SocketAsyncEventArgs 进行高效率 异步发送和消息获取。
    1.   
      public void SendAync(byte[] sendBytes)        {            SocketAsyncEventArgs sendSocketArgs = GlobalConfig.SendPool.Pop();            sendSocketArgs.UserToken = this;            sendSocketArgs.SetBuffer(sendBytes, 0, sendBytes.Length);            this.ClientSocket.SendAsync(sendSocketArgs);        }

       

2. Socket 与 WebSocket进行相互通信

  1. 前端Html5  WebSocket搭建
  2. Socket 接收和发送方法改进 支持 WebSocket。

 

其他:

  1. java对于 Socket的支持 ,及 ReadLine 造成的IO阻塞。
  2. 异常捕获,及废弃Socket处理

 

转载于:https://www.cnblogs.com/shikyoh/p/4588403.html

你可能感兴趣的文章
HDU - 6115 Factory (LCA 倍增)
查看>>
unity客户端与c++服务器之间的简单通讯_1
查看>>
Python_反射
查看>>
Codeforces-963 D Frequency of String
查看>>
MyBatis-mybatis全局映射文件解析
查看>>
WebApi 跨域解决方案 --CORS
查看>>
MySQL系列详解五: xtrabackup实现完全备份及增量备份详解-技术流ken
查看>>
单独编译Android源代码中的模块
查看>>
manjaro安装mysql5.7
查看>>
记录零散的知识点
查看>>
H5上传图片并使用canvas制作海报
查看>>
springmvc学习笔记
查看>>
LRU算法的设计
查看>>
Java util包中常用的类和方法
查看>>
[R] 之 管理工作空间函数
查看>>
将windows目录共享到linux
查看>>
计算机是如何启动的
查看>>
Python的raw_input语句包含中文,在Windows环境CMD中显示乱码的解决方法
查看>>
HIbernate学习笔记3 之 缓存和 对象的三种状态
查看>>
2015.3.12Arinc424 Tools中SiniArincCls.csParserFile(string sFile)函数正则表达式理解
查看>>