Ejemplo n.º 1
0
        private void OnRead(IAsyncResult ar)
        {
            StateObject state  = ar.AsyncState as StateObject;
            Socket      client = state.socket;

            try
            {
                int byteRead = client.EndReceive(ar);

                //包尺寸有问题,断线处理
                if (byteRead < 1)
                {
                    if (onConnectChangedAction != null)
                    {
                        onConnectChangedAction(ConnectType.DisConnect, client);
                    }
                    Console.WriteLine("client disconned!" + client.RemoteEndPoint);
                    return;
                }

                lock (lockObj)
                {
                    SocketData data;
                    if (SocketData.DeserializeData(state.buff, byteRead, out data))
                    {
                        Console.WriteLine("read : " + data.cn + "_" + data.module + "_" + data.cmd + " : " + data.attach.ToString());
                        if (onReceiveAction != null)
                        {
                            onReceiveAction(data);
                        }
                    }
                    Array.Clear(state.buff, 0, state.buff.Length);
                }
                client.BeginReceive(state.buff, 0, state.buff.Length, SocketFlags.None, new AsyncCallback(OnRead), state);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Ejemplo n.º 2
0
    private void OnRead(IAsyncResult ar)
    {
        int byteRead = 0;

        try
        {
            lock (client.GetStream())
            {
                byteRead = client.GetStream().EndRead(ar);
            }

            if (byteRead < 1)
            {
                Console.WriteLine("connect is lost");
                this.Close();
                return;
            }

            SocketData data;

            if (SocketData.DeserializeData(buff, byteRead, out data))
            {
                Console.WriteLine("read : " + data.cn + "_" + data.module + "_" + data.cmd + " : " + data.attach.ToString());
            }

            lock (client.GetStream())
            {
                Array.Clear(buff, 0, buff.Length);
                client.GetStream().BeginRead(buff, 0, buff.Length, new AsyncCallback(OnRead), null);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);

            this.Close();
        }
    }