supersocket client https://www.cnblogs.com/franklin2018/p/11494747.html

https://www.cnblogs.com/franklin2018/p/11494747.html

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

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

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

  • TerminatorReceiveFilter
  • BeginEndMarkReceiveFilter
  • FixedHeaderReceiveFilter
  • FixedSizeReceiveFilter
  • CountSpliterReceiveFilter
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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停止发送数据  

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