public void AcceptCallback(IAsyncResult ar)
        {
            // Create the state object.
            ReadState readState = new ReadState();

            try
            {
                // Signal the main thread to continue.
                allDone.Set();

                // Get the socket that handles the client request.
                Socket listener = (Socket)ar.AsyncState;
                Socket handler  = listener.EndAccept(ar);

                string sessionId = xxTCPClients.AssignSessionId();
                LOG.InfoFormat("({2}) New client:{0},sessionId:{1}", handler.RemoteEndPoint, sessionId, Name);

                xxClient client = new xxClient();
                client.socket    = handler;
                client.SessionId = sessionId;
                xxTCPClients.Add(client.SessionId, client);
                LOG.InfoFormat("({1}) Clients count:{0}", xxTCPClients.ClientCount, Name);

                readState.workSocket = handler;
                readState.sessionId  = client.SessionId;

                readState.HeaderBytes = new byte[HeaderLength];
                handler.BeginReceive(readState.HeaderBytes, 0, HeaderLength, SocketFlags.None, new AsyncCallback(ReadHeadCallback), readState);
            }
            catch (Exception e)
            {
                ReadException(e, readState);
            }
        }
 public void Send(string sessionId, xxTCPMsg msg, bool closeClient)
 {
     try
     {
         // Convert the string data to byte data using ASCII encoding.
         //            byte[] byteData = Encoding.ASCII.GetBytes(data);
         if (string.IsNullOrEmpty(sessionId))
         {
             throw new Exception("Session id is null!");
         }
         xxClient client = xxTCPClients.GetClient(sessionId);
         if (client == null)
         {
             throw new Exception("Not found client by session:" + sessionId);
         }
         LOG.DebugFormat("({2}) Send {0} bytes to {1}", msg.MsgBytes.Length, client.socket.RemoteEndPoint, Name);
         if (PrintSendHex)
         {
             PrintUtils.PrintHex(msg.MsgBytes);
         }
         SendState state = new SendState();
         state.CloseClient  = closeClient;
         state.RemoteSocket = client.socket;
         state.Client       = client;
         state.Msg          = msg;
         // Begin sending the data to the remote device.
         client.socket.BeginSend(msg.MsgBytes, 0, msg.MsgBytes.Length, 0,
                                 new AsyncCallback(SendCallback), state);
     }
     catch (Exception e)
     {
         ReadException(e, null);
     }
 }
Beispiel #3
0
 public static void Add(string sessionId, xxClient socket)
 {
     clientSockets.Add(sessionId, socket);
 }