Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
536 views
in Technique[技术] by (71.8m points)

c# - TCP server with multiple Clients

I am working on TCP server/client application.

My question is:

My server application starts a new thread and blocks it until connection is accepted the listenforClient method

But how can I manage the connections when multiple Clients are connected to my server and they request different things at the same time how can i manage that client 1 gets info its need and same for client 2.

It's multithreaded, so multiple Clients can connect but how can i process the request. I don't want to put everything in 1 method what than would.

Thanks in Advance

private void serverstart()
    {
        this.tcplistener = new TcpListener(IPAddress.Any, 49151);
        this.listenThread = new Thread(new ThreadStart(ListenForClients));
        this.listenThread.Start();
    }

    private void ListenForClients()
    {
        this.tcplistener.Start();

        while (true)
        {
            //blocks until a client has connected to the server
            TcpClient client = this.tcplistener.AcceptTcpClient();


            // here was first an message that send hello client
            //
            ///////////////////////////////////////////////////

            //create a thread to handle communication
            //with connected client
            Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));

            clientThread.Start(client);
        }
    }

    private void HandleClientComm(object client)
    {
        TcpClient tcpClient = (TcpClient)client;
        NetworkStream clientStream = tcpClient.GetStream();

        byte[] message = new byte[4096];
        int bytesRead;

        while (true)
        {
            bytesRead = 0;

            try
            {
                //blocks until a client sends a message
                bytesRead = clientStream.Read(message, 0, 4096);
            }
            catch
            {
                //a socket error has occured
                break;
            }

            if (bytesRead == 0)
            {
                //the client has disconnected from the server
                break;
            }

            //message has successfully been received
            ASCIIEncoding encoder = new ASCIIEncoding();

            bufferincmessage = encoder.GetString(message, 0, bytesRead);


            if (System.Text.RegularExpressions.Regex.IsMatch(bufferincmessage, Properties.Settings.Default.REQLogin, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
            {
                bufferincmessageresult = bufferincmessage.Split('^');
                nickname_Cl = bufferincmessageresult[1];
                password_Cl = bufferincmessageresult[2];
                getuserdata_db();
                login();

                byte[] buffer = encoder.GetBytes(inlogmessage);

                clientStream.Write(buffer, 0, buffer.Length);
                clientStream.Flush();
            }


        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your client will be dispatched in different threads, so they will not intersect. You just need to add something like "DispatchMethod" where your messages will be processed.

using System.Text.RegularExpressions;
...

if (Regex.IsMatch(bufferincmessage, Properties.Settings.Default.REQLogin, RegexOptions.IgnoreCase))
{
    ...
}
else if (Regex.IsMatch(bufferincmessage, /*some of your command1*/, RegexOptions.IgnoreCase))
{
    ...
}
else if (Regex.IsMatch(bufferincmessage, /*some of your command1*/, RegexOptions.IgnoreCase))
{
    ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...