zoukankan      html  css  js  c++  java
  • SuperSocket 学习笔记-客户端

    客户端:

    定义

     private AsyncTcpSession client;

     初始化 

    client = new AsyncTcpSession();
    client.Connected += ClientOnConnected;
    client.Closed += ClientOnClosed;
    client.DataReceived += ClientOnDataReceived;
    ThreadPool.QueueUserWorkItem(ConnectServer_Loop);

    事件

            private void ClientOnDataReceived(object sender, DataEventArgs e) { 
                var dat = Encoding.Default.GetString(e.Data.Take(e.Length).ToArray());
            //使用有效数据长度截取数组,可消除数据中的多余空字符 textBox1.AppendText($
    "收到数据:{dat}"); } private void ClientOnClosed(object sender, EventArgs e) { textBox1.AppendText($"服务器连接关闭{Environment.NewLine}"); } private void ClientOnConnected(object sender, EventArgs e) { textBox1.AppendText($"已连接服务器{Environment.NewLine}"); }

    持续线程

     private void ConnectServer_Loop(object state) {
                if (ConnectServer_Loop_workState) return;
                ConnectServer_Loop_workState = true;
                while (ConnectServer_Loop_workState) {
                    Thread.Sleep(1000);
                    if (!client.IsConnected) {
                        try {
                            client.Connect(new IPEndPoint(IPAddress.Parse("192.168.15.2"), 57900)); 
                        } catch {}
                    }  
                }
    
                ConnectServer_Loop_workState = false;
            }
    
            private bool ConnectServer_Loop_workState;
            private void ConnectServer_Loop_Stop() => ConnectServer_Loop_workState = false;

     此外,客户端发送数据后必须在结尾添加回车换行标志,否则服务端不能触发接收消息事件

  • 相关阅读:
    使用PHP类库PHPqrCode生成二维码
    40+个对初学者非常有用的PHP技巧
    (高级篇)jQuery学习之jQuery Ajax用法详解
    lerna管理前端模块实践
    Node.js:深入浅出 http 与 stream
    从koa-session源码解读session本质
    Elastichsearch实践
    Linux代理搭建TinyProxy
    linux常用命令
    node前后端同构的踩坑经历
  • 原文地址:https://www.cnblogs.com/vonly/p/11171682.html
Copyright © 2011-2022 走看看