. Net TCP exploration - TCP server development (listening to multiple client requests at the same time)

Keywords: ASP.NET github encoding

Recently, I read the works written by the great God in the garden.( Interviewer, don't ask me three handshake and four wave again. )Can't help writing a program to test it.

Many examples have been found on the Internet, most of which only implement TCP point-to-point communication, but in practical applications, a server port often listens to messages sent by multiple clients.

Test tool download: https://download.csdn.net/download/nbyanghuichao/11872360
In this example, System.Threading is used to realize multithreaded monitoring. Only the core code is introduced below, message prompt and error handling are omitted, and the complete code can be obtained from my GitHub: https://github.com/FB208/CodeSpace/tree/master/CodeSpace.CSharp/TCP.Client

Data statement:

private string _ip;//IP
private int _port;//port
//Client collection
public static List<TcpClientModel> clients = new List<TcpClientModel>
private static byte[] bytes = new byte[1024 * 100];
/// <summary>
///For storing clients
/// </summary>
public class TcpClientModel
{
    /// <summary>
    /// IP:Port
    /// </summary>
    public string RemoteEndPoint { get; set; }
    /// <summary>
    ///Client link object
    /// </summary>
    public TcpClient TcpClient { get; set; }
}

Start listening:

///Start listening
void Init()
{
    try
    {
        IPAddress ip = IPAddress.Parse(_ip);
        int port = _port;
        TcpListener listener = new TcpListener(ip, port);
        //lsnrctl start
        listener.Start();
        tb_console.AppendText($"Listener...\r\n");
        //Asynchronous receive recursive loop receive multiple clients
        listener.BeginAcceptTcpClient(new AsyncCallback(GetAcceptTcpclient), listener);
    }
    catch (Exception ex)
    {
        
    }
}

Receiving client:

private void GetAcceptTcpclient(IAsyncResult State)
{
    //Handle multiple client access
    TcpListener listener = (TcpListener)State.AsyncState;
    //Client request received
    TcpClient client = listener.EndAcceptTcpClient(State);
    //Save to client collection
    clients.Add(new TcpClientModel() { TcpClient = client, RemoteEndPoint = client.Client.RemoteEndPoint.ToString() });

    //Enable threads to receive data from clients continuously
    Thread myThread = new Thread(() =>
    {
        ReceiveMsgFromClient(client);
    });
    myThread.Start();
    listener.BeginAcceptTcpClient(new AsyncCallback(GetAcceptTcpclient), listener);
}

To receive messages and respond to clients:

private void ReceiveMsgFromClient(object reciveClient)
{
    TcpClient client = reciveClient as TcpClient;
    if (client == null)
    {
        return;
    }
    while (true)
    {
        try
        {
            NetworkStream stream = client.GetStream();
            int num = stream.Read(bytes, 0, bytes.Length); //Read the data into the result and return the character length >
            if (num != 0)
            {
                //Assign string value to str for data stored in stream in byte array
                //Here is the received client message
                string str = Encoding.UTF8.GetString(bytes, 0, num);

                //Return a message to the client
                string msg = "Your message has been received by the server[" + str + "]";

                bool result = TCPHelper.SendToClient(client, msg, out msg);
                if (!result)
                {
                    //fail in send
                }
            }
            else
            {   
                //Note that when num=0, the client is disconnected and the loop needs to be ended. Otherwise, the loop will be stuck.
                break;
            }
        }
        catch (Exception ex)
        {
            //Link failure remove bad client from collection
            clients.Remove(clients.FirstOrDefault(m => m.RemoteEndPoint == client.Client.RemoteEndPoint.ToString()));
            break;
        }

    }
}

Tool class to send messages from server to client:

public static class TCPHelper
{
    public static bool SendToClient(TcpClient client, string message,out string errorMsg)
    {
        try
        {
            byte[] bytes = new byte[1024 * 100];
            bytes = Encoding.UTF8.GetBytes(message);
            NetworkStream stream = client.GetStream();
            stream.Write(bytes, 0, bytes.Length);
            stream.Flush();
            errorMsg = "";
            return true;
        }
        catch (Exception ex)
        {
            errorMsg = ex.Message;
            return false;
        }
    }
}

Test effect:

For complete code, please pay attention to: https://github.com/FB208/CodeSpace/tree/master/CodeSpace.CSharp/TCP.Client

Posted by FeralReason on Fri, 18 Oct 2019 07:44:45 -0700