C# Socket简单的实现一对多/多对一通讯

2015-4-24 Linyuting.cn 博客札记

    C# Socket网络通讯,用线程的方法可以实现一对多/多对多通讯。这是从我某个学习项目截取的一段代码

    

    class Server
    {
        int socketNum = 0;
        private List<Thread> clientSocketThread = new List<Thread>();
        private List<Socket> clientSocket = new List<Socket>();

        private void ServerMainThread()
        {
            IPEndPoint server = new IPEndPoint("0.0.0.0", 59999);
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            serverSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            serverSocket.Bind(server);
            serverSocket.Listen(100);

            
            while (true)
            {
                Int32 i = socketNum++;
                Socket tempSock = serverSocket.Accept();
                clientSocket.Add(tempSock);
                clientSocketThread.Add(new Thread(new ParameterizedThreadStart(AcceptMessage)));//这里的
                clientSocketThread[i].Start(i);
            }
        }

        private void AcceptMessage(object o)
        {

            int i = (int)o;
            //这里只要调用clientSocket[i]即可对这个连接的客户socket进行操作了
        }
}


标签: c#

发表评论:

本站由emlog驱动 粤ICP备15042739号