开发者

How to handle multiple TCP clients for communication

I'm developing multi client TCP/IP server application that may receive some commands from different clients and on the basis of these commands the server would perform some actions and send back the response to client accordingly.

My question is how to handle multiple clients to send the relevant data back to that particular client after process开发者_开发问答ing. How to pass the reference of TCP client when sending data to server and how to preserve it so that the response can be sent back to its relevant TCPClient.

I'm using TCPlistner for creating TCPClient object. That is oTCPClient = oTCPListener.AcceptTcpClient();. So how to create relevant NetworkStream for each TCPClient for communication.


I would create a ConnectedClient class which takes a TCPClient in the constructor, then start a thread in that object which reads the NetworkStream of the TCPClient for incoming data. You could also have a method in ConnectedClient for sending data. Whenever you receive data and want to reply to or forward the message, you can call SendData on one or more of the stored ConnectedClient objects.


Here is a example of a server that can handle multiple clients and respond to multiple clients

class MultyClientServer
{
    private static int bufferSize = 2048;
    private static byte[] buffer = new byte[bufferSize];
    private static List<Socket> clientSockets = new List<Socket>();
    private static Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);


    static void Main(string[] args)
    {
        Console.Title = "Server";
        SetupServer();
        Console.ReadKey();
        CloseAllSockets();
    }

    private static void SetupServer()
    {
        Console.WriteLine("Settings Up Server Plz Wait");
        serverSocket.Bind(new IPEndPoint(IPAddress.Any, YOUR PORT HERE));
        serverSocket.Listen(10);
        serverSocket.BeginAccept(new AsyncCallback(CallBack), null);
        Console.WriteLine("Server Made");
    }

    private static void CallBack(IAsyncResult e)
    {
        try
        {
            Socket socket = serverSocket.EndAccept(e);
            clientSockets.Add(socket);
            Console.WriteLine("Client Connected");
            socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), socket);
            serverSocket.BeginAccept(new AsyncCallback(CallBack), null);
        }
        catch (Exception ex) { Console.WriteLine(ex.Message); }
    }

    private static void ReceiveCallBack(IAsyncResult e)
    {
        try
        {
            Socket socket = (Socket)e.AsyncState;
            int received;
            try
            {
                received = socket.EndReceive(e);
            }
            catch (SocketException)
            {
                Console.WriteLine("Client forcefully disconnected");
                socket.Close();
                clientSockets.Remove(socket);
                return;
            }
            byte[] dataBuf = new byte[received];
            Array.Copy(buffer, dataBuf, received);

            string text = Encoding.ASCII.GetString(dataBuf);
            Console.WriteLine("Client request: " + text);

            string response = string.Empty;


            try
            {
                if (command.ToLower() == "What Time is it")
                {
                    response = DateTime.Now.ToString();
                }
                else if (command.ToLower() == "Whats your name")
                {
                    response = "Tyler Gregorcyk";
                }
                else
                {
                    response = "Invaled";
                }
            }
            catch (Exception et) { Console.WriteLine(et.Message); socket.Close(); clientSockets.Remove(socket); }


            if(response == string.Empty)
            {
                response = "Invaled";
            }

            if (response != string.Empty)
            {
                Console.WriteLine("Sent To Client: " + response);
                byte[] data = Encoding.ASCII.GetBytes(response);
                socket.Send(data);
                serverSocket.BeginAccept(new AsyncCallback(CallBack), null);
            }

            conn.Close();
            socket.BeginReceive(buffer, 0, bufferSize, SocketFlags.None, ReceiveCallBack, socket);
        }
        catch (Exception) { }
    }

    private static void CloseAllSockets()
    {
        foreach (Socket socket in clientSockets)
        {
            socket.Shutdown(SocketShutdown.Both);
            socket.Close();
        }

        serverSocket.Close();
    }
}

BTW this is a edited version of a tutorial on YouTube: https://www.youtube.com/watch?v=xgLRe7QV6QI

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜