Example #1
0
        private void AsyncAcceptClient(IAsyncResult asyncResult)
        {
            //获取客户端套接字

            Socket clientSocket = serverSocket.EndAccept(asyncResult);

            string clientIpPort = clientSocket.RemoteEndPoint.ToString();

            Debug.Log("SocketServer.AsyncAcceptClient 客户端连接:" + clientIpPort);

            try
            {
                Loom.QueueOnMainThread(() =>
                {
                    OnClientConnect?.Invoke(clientIpPort);
                });
            }
            catch (Exception e)
            {
                Debug.LogError("server ex------>" + e.ToString());
            }

            Debug.Log(string.Format("SocketServer.AsyncAcceptClient 客户端{0}请求连接...", clientIpPort));

            NetworkStream networkSteam = new NetworkStream(clientSocket, false);

            ServerSession session = new ServerSession(clientIpPort, clientSocket, networkSteam);

            session._SocketPackMgr.OnProcessOnMsg = OnProcessOneMsg;

            if (!SessionDic.ContainsKey(session.ID))
            {
                SessionDic.Add(session.ID, session);
            }
            else
            {
                Debug.LogError("SocketServer.AsyncAcceptClient SessionPool中已经包含ip:" + session.ID + " 加入sessionPool失败");
            }

            Debug.Log("SocketServer.AsyncAcceptClient nmbnmb");

            //开始接受一个客户端的数据
            session._SocketPackMgr.ReadOnceFromSocket();

            //准备接受下一个客户端
            serverSocket.BeginAccept(new AsyncCallback(AsyncAcceptClient), serverSocket);
        }
Example #2
0
        private void CloseSession(ServerSession session)
        {
            string ip = session.ID;

            var socket = session._SocketPackMgr._Socket;

            if (socket == null)
            {
                Debug.LogError("SocketServer.CloseSession 关闭失败  serverSocket == null");
                return;
            }

            Debug.Log("SocketServer.CloseSession ip:" + ip);

            if (!socket.Connected)
            {
                Debug.LogError("SocketServer.CloseSession 关闭失败  serverSocket.Connected == false");
                return;
            }

            try
            {
                socket.Shutdown(SocketShutdown.Both);
            }
            catch (Exception ex)
            {
                Debug.LogError("SocketServer.CloseSession Shutdown Exception :" + ex.ToString());
            }

            try
            {
                socket.Close();
            }
            catch (Exception ex)
            {
                Debug.LogError("SocketServer.CloseSession Close Exception :" + ex.ToString());
            }
        }