简体   繁体   中英

Multiple Clients in Client Server app in C#

using resources at http://www.developerfusion.com i came up with the following server code. It works well for single client. How can i make it for multiple clients. I tried adding array and different instances of the beiginreceive but was unable to. The server code:

class Program
{
    public static AsyncCallback pfnWorkerCallBack;
    public static Socket m_socListener;
    public static Socket m_socWorker;

    static void Main(string[] args)
    {
        try
        {
            //create the listening socket...
            m_socListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, 8221);
            //bind to local IP Address...
            m_socListener.Bind(ipLocal);
            Console.WriteLine("UCManager Started");
            //start listening...
            m_socListener.Listen(4);
            // create the call back for any client connections...
            m_socListener.BeginAccept(new AsyncCallback(OnClientConnect), null);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

        Console.ReadLine();
    }

    public static void OnClientConnect(IAsyncResult asyn)
    {
        try
        {
            m_socWorker = m_socListener.EndAccept(asyn);

            WaitForData(m_socWorker);
        }
        catch (Exception se)
        {
            Console.WriteLine(se.Message);
        }

    }
    public class CSocketPacket
    {
        public System.Net.Sockets.Socket thisSocket;
        public byte[] dataBuffer = new byte[1];
    }

    public static void WaitForData(System.Net.Sockets.Socket soc)
    {
        try
        {
            if (pfnWorkerCallBack == null)
            {
                pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
            }
            CSocketPacket theSocPkt = new CSocketPacket();
            theSocPkt.thisSocket = soc;
            // now start to listen for any data...
            soc.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, pfnWorkerCallBack, theSocPkt);
        }
        catch (SocketException se)
        {
            Console.WriteLine(se.Message);
        }

    }

    public static void OnDataReceived(IAsyncResult asyn)
    {
        try
        {
            CSocketPacket theSockId = (CSocketPacket)asyn.AsyncState;
            //end receive...
            int iRx = 0;
            iRx = theSockId.thisSocket.EndReceive(asyn);
            char[] chars = new char[iRx + 1];
            Decoder d = Encoding.UTF8.GetDecoder();
            int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);
            String szData = new String(chars);
            Console.WriteLine(szData);
            int code = Convert.ToInt32(szData); 

            WaitForData(m_socWorker);
        }

        catch (Exception se)
        {
            Console.WriteLine(se.Message);
        }
    }

}

}

EDIT: Ok i did something on the lines of Async TCP Server for multiple Clients .

public static void OnClientConnect(IAsyncResult asyn)
        {
            try
            {
                Socket m_socWorkerInstance = m_socListener.EndAccept(asyn);
                clientSocketList.Add(m_socWorkerInstance);

                WaitForData(m_socWorkerInstance);
            }
            catch (ObjectDisposedException)
            {
                System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
            }
            catch (SocketException se)
            {
                Console.WriteLine(se.Message);
            }

        }
public static void WaitForData(System.Net.Sockets.Socket soc)
        {
            try
            {
                if (pfnWorkerCallBack == null)
                {
                    pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
                }
                CSocketPacket theSocPkt = new CSocketPacket();
                theSocPkt.thisSocket = soc;
                // now start to listen for any data...
                soc.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, pfnWorkerCallBack, theSocPkt);
                m_socListener.BeginAccept(new AsyncCallback(OnClientConnect), null);
            }
            catch (SocketException se)
            {
                Console.WriteLine(se.Message);
            }

        }

Now i am able to connect two clients but not able to communicate ...I am unable to send message from server to client...any suggestions...also should i have different read functions for both clients if i connect with two client???

You call BeginAccept only once, so after one client has been accepted, your server won't accept any new connections. You should call BeginAccept again after accepting a connection.

Ok i was able to solve it using Async TCP Server for multiple Clients :

public static void OnClientConnect(IAsyncResult asyn)
            {
                try
                {
                    Socket m_socWorkerInstance = m_socListener.EndAccept(asyn);
                    clientSocketList.Add(m_socWorkerInstance);

                    WaitForData(m_socWorkerInstance);
                }
                catch (ObjectDisposedException)
                {
                    System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
                }
                catch (SocketException se)
                {
                    Console.WriteLine(se.Message);
                }

            }
    public static void WaitForData(System.Net.Sockets.Socket soc)
            {
                try
                {
                    if (pfnWorkerCallBack == null)
                    {
                        pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
                    }
                    CSocketPacket theSocPkt = new CSocketPacket();
                    theSocPkt.thisSocket = soc;
                    // now start to listen for any data...
                    soc.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, pfnWorkerCallBack, theSocPkt);
                    m_socListener.BeginAccept(new AsyncCallback(OnClientConnect), null);
                }
                catch (SocketException se)
                {
                    Console.WriteLine(se.Message);
                }

            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM