C#中Client Server应用程序中的多个客户端

时间:2013-08-21 09:32:53

标签: c# visual-studio-2010 client-server

使用http://www.developerfusion.com处的资源我想出了以下服务器代码。它适用于单个客户端。我怎样才能为多个客户提供服务。我尝试添加数组和beiginreceive的不同实例,但无法。服务器代码:

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);
        }
    }

}

}

编辑:好的,我在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);
            }

        }

现在我能够连接两个客户端但无法通信...我无法从服务器向客户端发送消息...任何建议......我也应该为两个客户端提供不同的读取功能如果我连接两个客户端???

2 个答案:

答案 0 :(得分:2)

您只需拨打BeginAccept一次,因此在接受一个客户端后,您的服务器将不接受任何新连接。您应该在接受连接后再次致电BeginAccept

答案 1 :(得分:0)

好的我能够使用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);
                }

            }