supersocket client 的简单使用方法

由于需要在服务端和客户端持续通信,于是在网上找了好久的socket通信工具。刚开始想直接用.net自带的socket通信,后来担心不够稳定健壮,毕竟自己不专业。找来找去觉得supersocket还可以,但是说实话,他们的帮助文档写的真是太烂了,使用也不够简单易懂,折腾了一阵大致明白如何使用。

1,在nuget上引用supersocket.clientengine和supersocket.protobase

2,定义一个filter的类,protobase提供了5种预定义的方式,这里采用第二种,即定义数据头和尾的方式:

  • TerminatorReceiveFilter

  • BeginEndMarkReceiveFilter

  • FixedHeaderReceiveFilter

  • FixedSizeReceiveFilter

  • CountSpliterReceiveFilter

    class MyBeginEndMarkReceiveFilter : BeginEndMarkReceiveFilter<StringPackageInfo> { public MyBeginEndMarkReceiveFilter(string begin,string end) : base(Encoding.UTF8.GetBytes(begin), Encoding.UTF8.GetBytes(end)) { this.begin = begin; this.end = end; } string begin; string end; public override StringPackageInfo ResolvePackage(IBufferStream bufferStream) { //获取接收到的完整数据,包括头和尾 var body = bufferStream.ReadString((int)bufferStream.Length, Encoding.ASCII); //掐头去尾,只返回中间的数据 body = body.Remove(body.Length - end.Length, end.Length); body = body.Remove(0, begin.Length); return new StringPackageInfo("", body, new string[] { }); } }

3,封装一个简单的类。初始化类的时候设置好ip,端口,数据头和尾,然后设置要发送的数据属性data,然后调用startcomm方法开始每秒发送一次请求数据到服务器,订阅接收数据的事件newReceived。如果有需要可以随时更换data的内容,或者调用stopcomm停止发送数据  

1class socketClient 2 { 3 SuperSocket.ClientEngine.EasyClient client; 4 /// <summary> 5 /// 定义服务端的ip地址和端口,以及接收数据的头和尾,只有在头和尾之间的数据才算有效数据 6 /// </summary> 7 /// <param name="ip">ip地址</param> 8 /// <param name="port">服务端口</param> 9 /// <param name="startFilter">数据头</param> 10 /// <param name="endFilter">数据尾</param> 11 public socketClient(string ip, int port, string startFilter, string endFilter) 12 { 13 this.ip = ip; 14 this.port = port; 15 if (!string.IsNullOrEmpty(startFilter)) this.startFilter = startFilter; 16 if (!string.IsNullOrEmpty(endFilter)) this.endFilter = endFilter; 17 client = new SuperSocket.ClientEngine.EasyClient(); 18 client.Initialize(new MyBeginEndMarkReceiveFilter(this.startFilter,this.endFilter), onReceived); 19 } 20 string ip; 21 int port; 22 string startFilter = "!!!"; 23 string endFilter = "###"; 24 bool cycleSend = false; 25 /// <summary> 26 /// 要发送到服务端的数据 27 /// </summary> 28 public string data { get; set; } = "hello,this is super client\r\n"; 29 public void startComm() 30 {//开始循环发送数据 31 cycleSend = true; 32 System.Threading.Thread _thread = new System.Threading.Thread(sendData); 33 _thread.IsBackground = true; 34 _thread.Start(); 35 } 36 public void sendData() 37 {//采用线程间隔一秒发送数据,防止界面卡死 38 while (cycleSend) 39 { 40 if (!client.IsConnected) 41 { 42 connectToServer(ip, port); 43 } 44 if (client.IsConnected) 45 { 46 client.Send(Encoding.ASCII.GetBytes("hello,this is super client\r\n")); 47 } 48 System.Threading.Thread.Sleep(1000); 49 } 50 } 51 public void stopComm() 52 {//停止循环发送数据 53 cycleSend = false; 54 } 55 public async void connectToServer(string ip, int port) 56 {//连接到服务端 57 var connected = await client.ConnectAsync(new IPEndPoint(IPAddress.Parse(ip), port)); 58 if (connected) 59 { 60 //发送连接信息 61 client.Send(Encoding.ASCII.GetBytes("build connection")); 62 } 63 } 64 public System.EventHandler newReceived; 65 private void onReceived(StringPackageInfo stringPackageInfo) 66 {//当读取到数据,触发一个事件,方便外部接收数据 67 if (newReceived != null) 68 { 69 newReceived(stringPackageInfo.Body, new EventArgs()); 70 } 71 } 72 }
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )