socket

server部分

这部分完成总的服务端发布和客户端分配。

class Server
    {
        private static Socket socket;
        Dictionary<int, Client> clients;
        int latestIndex = 0;
        List<int> removedIndexes;

        public Server(int port)
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6666));
            socket.Listen(0);
        }
        void startAccept()
        {
            socket.BeginAccept(acceptCallBack, null);
        }
        void acceptCallBack(IAsyncResult iar)
        {
            Socket clientSocket = socket.EndAccept(iar);
            if (removedIndexes.Count > 0)
            {
                int index = removedIndexes[0];
                removedIndexes.RemoveAt(0);
                clients.Add(index, new Client(this,clientSocket, index));
            }
            else
            {
                clients.Add(latestIndex, new Client(this,clientSocket, latestIndex));
                latestIndex++;
            }
        }
        public void removeClient(Client client)
        {
            clients.Remove(client.indexInDic);
            removedIndexes.Add(client.indexInDic);
        }
    }
class Client
    {
        private Socket clientSocket;
        Server server;
        public const int BUFFER_SIZE = 1024;
        public byte[] buffer = new byte[BUFFER_SIZE];
        public int indexInDic { get; }

        public Client(Server server, Socket clientSocket,int indexInDic)
        {
            this.server = server;
            this.indexInDic = indexInDic;
            this.clientSocket = clientSocket;
            startReceive();
        }
        void startReceive()
        {
            clientSocket.BeginReceive(buffer,0,BUFFER_SIZE, SocketFlags.None, ReceiveCallback,null);
        }
        void handleReceive()
        {

        }
        void ReceiveCallback(IAsyncResult iar)
        {
            try
            {
                if (clientSocket == null || clientSocket.Connected == false) {
                    server.removeClient(this);
                    return;
                } 
                int len = clientSocket.EndReceive(iar);
                Console.WriteLine("接收");
                if (len == 0)
                {
                    Console.WriteLine("接收数据为0");
                    close();
                    return;
                }

                handleReceive();
                startReceive();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                close();
            }
        }
        private void close()
        {
            Console.WriteLine("断开");
            clientSocket.Close();
            server.removeClient(this);
        }
    }
© 2021 hanbaoaaa record.浙ICP备20005263号
asdad
联系方式 asdasd
2021-5-8 4:19
sss
回复数 (0) 点击展开
加载更多

新增评论

称呼
联系方式
邮箱(选填)
内容

提交

取消