C# open source class library simpletcp

Time:2021-9-27

brief introduction

When we often need to implement TCP client or server in our work, it will be troublesome and boring to write by ourselves every time, and the use of supersocket library is too large. It can be used at this timeSimpleTCPOf course, it is limited to c# language.

SimpleTCPIs a simple and very useful. Net library for handling repetitive tasks of starting and using TCP sockets (client and server). It is very easy to use and has less code. Its internal is not a directly used socket, but in theTcpClientThe interface is simpler and clearer.

Its main features are as follows:

  • Simple source code: there are only a few classes in the source code, and each class is small. On the basis of understanding the usage of tcpclient, you can understand it without comments.
  • Single function: unlike other libraries, it has many functions. It only focuses on the implementation of simple TCP client and server, and does not need to worry about increasing the complexity of the system.
  • Easy to use: the following examples will explain in detail. Starting a client or server requires only a few lines of code. It is also very simple to expand functions.

Talk about its shortcomings (in my opinion, it is completely acceptable):

  • Update stopped: the last update was in 2017, but the function of the library is relatively simple and single, and there are not so many updated contents.
  • Performance is not optimal: the bottom layer is based on tcpclient, and the performance is bound not to be too high, but it can be used wherever tcpclient can be used.

usage method

Direct reference in projectSimpleTCP.dllThe DLL file can be compiled by installing nuget or downloading the source code from GitHub.
Simpletcp has a special character segmentation string protocol, which can be used directly or inDataReceivedImplement your own protocol in the event handler.

Implementation client

The code for implementing a client is as follows:

//Initialization
var client = new SimpleTcpClient();            

//Set the encoding format. The default is utf8
client.StringEncoder = System.Text.ASCIIEncoding.ASCII;
//Set the separator. The default is 0x13
client.Delimiter = Encoding.ASCII.GetBytes("\r")[0];

//After receiving the event of segmented data, the event will be triggered when the separator is encountered
client.DelimiterDataReceived += (sender, msg) => 
{
    Console.WriteLine("DelimiterStr-"+DateTime.Now.ToString()+ msg.MessageString);
};

//For events that receive data, you can implement your own protocol here
client.DataReceived += (sender, msg) => 
{
    //Byte array
    Console.WriteLine("Data:"+BitConverter.ToString(msg.Data));
    //String message
    Console.WriteLine("ReceivedStr:" + msg.MessageString);
};

DelimiterDataReceivedandDataReceivedTwo different byte linked lists are used internally, which do not affect each other. thisTry not to do time-consuming operations in the two event handlers, otherwise the subsequent data reception will be affected

Simpletcp has no heartbeat and reconnection functions, and the attribute that feeds back the connection status of the client is not found (the connection status of the internal tcpclient is not recommended). We can directly extend these functions. The code is as follows:

bool exit = false;
bool connected = false;
Task.Factory.StartNew(() => 
{
    while (!exit) 
    {
        try
        {
            if (connected)
            {
                //Send heartbeat
                client.Write("");
                Task.Delay(10000).Wait();
            }
            else
            {
                //Disconnection reconnection
                client.Connect("127.0.0.1", 4196);
                connected = true;
                Task.Delay(1000).Wait();
            }
        }
        catch (Exception)
        {
            connected = false;
            client.Disconnect();
        }
    }               
    
}, TaskCreationOptions.LongRunning);

Copy the above code to the main function of the console in order, and then add the following code to send and receive data:

while (true) 
{
    string strLine = Console.ReadLine();
    if (strLine == "esc") 
    {
        exit = true;
        client.Disconnect();
        return;
    }
    if (connected) 
    { 
        //Get the message replied by the server, wait up to 3 seconds, and return in advance when receiving the message
        //You can also use write and writeline methods to send data, and writeline will automatically add the set separator after it
        var replyMsg = client.WriteLineAndGetReply(strLine, TimeSpan.FromSeconds(3));
        if (replyMsg != null) 
        {
            Console.WriteLine(replyMsg);
        }
    }
}

Note:Writelineandgetreply internally usesDataReceived, the separator is not automatically removed

Implement server

The function of the server is relatively simple. The received split data is processed and returned to the client. The code is as follows:

//Initialization
var server = new SimpleTcpServer();
//Set the encoding format. The default is utf8
server.StringEncoder = System.Text.ASCIIEncoding.ASCII;
server.Delimiter =  Encoding.ASCII.GetBytes("\r")[0];

//Split data receive event
server.DelimiterDataReceived += (sender, msg) => 
{
    Console.WriteLine(msg.TcpClient.Client.RemoteEndPoint.ToString()+":" + msg.MessageString);
    msg.ReplyLine("Reply-" + msg.MessageString);
};

//Data receiving data
server.DataReceived += (sender, msg) =>
{
    Console.WriteLine(msg.TcpClient.Client.RemoteEndPoint.ToString() + ":" + msg.MessageString);
};

//Client connection events
server.ClientConnected += (sender, msg) => 
{
    Console.WriteLine("ClientConnected:" + msg.Client.RemoteEndPoint.ToString());
};

//Client disconnect event
server.ClientDisconnected += (sender, msg) =>
{
    Console.WriteLine("ClientDisconnected:" + msg.Client.RemoteEndPoint.ToString());
};

//Start listening
server.Start(4196);
//Listening IP
var listeningIps = server.GetListeningIPs();
//V4ip monitored
var listeningV4Ips = server.GetListeningIPs().Where(ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);



Task.Factory.StartNew(() =>
{
    while (true)
    {   
        //Connection number monitoring
        int clientsConnected = server.ConnectedClientsCount;
        Console.writeline ("number of clients currently connected:" + clientsconnected);
        Task.Delay(10000).Wait();
    }

}, TaskCreationOptions.LongRunning);            
Console.ReadLine();

//Stop listening
server.Stop();
Console. Writeline ("stop server!");
Console.ReadLine();

summary

The above code is mainly to show the functions of the library. In actual use, there may be only a few lines of code. Projects with low performance requirements can be used.

The source code links of the project and library are as follows: