Share a lightweight TCP\IP communication library (Simple TCP)

Foreword:

In the project, most of the server and the client maintain a long-term connection, but later encountered a project that communicates with the Mes system on the production line. Because the on-site network often has abnormal connections, I thought of it. This short connection method (the server is in the listening state for a long time, and the client only connects when it needs to send and receive data, and disconnects again after sending and receiving data). Later, I accidentally found Simple TCP, a useful external library, and the development is also very simple and friendly! Great for loafing. . .

1. Form layout:

insert image description here

2. Server code:

//初始化服务器
public SimpleTcpServer server = new SimpleTcpServer();

/// <summary>
/// 监听端口
/// </summary>
public void StartListen()
{
    
    
     //设置编码格式,默认是UTF8
     server.StringEncoder = System.Text.ASCIIEncoding.ASCII;
     server.Delimiter = Encoding.ASCII.GetBytes("\r")[0];

     //数据接收数据
     server.DataReceived += (sender, msg) =>
     {
    
    
           // 接收字节数组
           // byte[] bytData = msg.Data; 

           WriteMsg(msg.MessageString);
      };

      //客户端连接事件
      server.ClientConnected += (sender, msg) =>
      {
    
    
            WriteMsg("ClientConnected:" + msg.Client.RemoteEndPoint.ToString());
      };

      //客户端断开事件
      server.ClientDisconnected += (sender, msg) =>
      {
    
    
            WriteMsg("ClientDisconnected:" + msg.Client.RemoteEndPoint.ToString());
      };

      //开始监听
      server.Start(IPAddress.Parse(txt_ServerIPAddress.Text.Trim()), Convert.ToInt32(nud_ServerPort.Value));

      Task.Factory.StartNew(() =>
      {
    
    
           while (true)
           {
    
    
                //连接数监控
                //int clientsConnected = server.ConnectedClientsCount;

                Task.Delay(1000).Wait();
            }

      }, TaskCreationOptions.LongRunning);
}

// 服务端发送数据
private void btn_ServerSend_Click(object sender, EventArgs e)
{
    
    
     server.Broadcast("Server to client: " + txt_ServerMsg.Text.Trim()); //发送数据
}

3. Client code:

//初始化客户端
public SimpleTcpClient client = new SimpleTcpClient();

/// <summary>
/// 连接到服务端
/// </summary>
public void StartConnect()
{
    
    
       //设置编码格式,默认是UTF8
       client.StringEncoder = System.Text.ASCIIEncoding.ASCII;
       //设置分隔符,默认是0x13
       client.Delimiter = Encoding.ASCII.GetBytes("\r")[0];

       //收到数据的事件,可以在这里实现自己的协议
       client.DataReceived += (sender, msg) =>
       {
    
    
            //将收到的字节数组转为string
            //string bytData = BitConverter.ToString(msg.Data);

            //字符串消息
            WriteMsg(msg.MessageString);
       };

       bool exit = false;
       bool connected = false;
       Task.Factory.StartNew(() =>
       {
    
    
           while (!exit)
           {
    
    
               try
               {
    
    
                   if (connected)
                   {
    
    
                       //发送心跳
                       client.Write("-");
                       Task.Delay(10000).Wait();
                    }
                   else
                   {
    
    
                       //断线重连
                       client.Connect(txt_ClientIPAddress.Text.Trim(), Convert.ToInt32(nud_ClientPort.Value));
                       connected = true;
                       Task.Delay(1000).Wait();
                    }
                 }
                 catch (Exception)
                 {
    
    
                        connected = false;
                        client.Disconnect();
                  }
              }
       }, TaskCreationOptions.LongRunning);
}

private void btn_ClientSend_Click(object sender, EventArgs e)
{
    
    
     client.Write("Client to server: " + txt_ClientMsg.Text.Trim());
}

4. Run the test:

insert image description here

5. DLL file:

insert image description here
Only 20k in size, this can be downloaded from the Internet, or you can private message me, and send it when you see it. . .

Guess you like

Origin blog.csdn.net/qq_34699535/article/details/127112054