Ejemplo n.º 1
0
        private void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                client = new TcpClient(Dns.GetHostName(), ChatUtil.Port);
                txtMessage.Append("Successfully connected to Server side.");
            }
            catch (SocketException socketEx)
            {
                txtMessage.Append("Failed to connect server:" + socketEx.Data);
                return;
            }
            stream = client.GetStream();
            writer = new BinaryWriter(stream);
            ChatMessageEntity messageEntity = new ChatMessageEntity();

            messageEntity.NickName       = loginName;
            messageEntity.MessageType    = ChatStateEnum.OnLine;
            messageEntity.MessageContent = string.Empty;
            messageEntity.RemoteEndPoint = client.Client.LocalEndPoint;
            this.Text += " 【" + client.Client.LocalEndPoint + "】";
            messageEntity.timeStamp = DateTime.Now;

            WriteToStream(messageEntity);


            heartbeatTimer.Enabled = true;
            heartbeatTimer.Start();

            Task.Run(() =>
            {
                reader = new BinaryReader(stream);
                ObjectInversion inversion = new ObjectInversion();
                int bufferLen             = client.ReceiveBufferSize;
                byte[] recvBytes          = new byte[bufferLen];
                while (true)
                {
                    reader.Read(recvBytes, 0, bufferLen);
                    ChatMessageEntity entity = inversion.DeSerializeTo(recvBytes) as ChatMessageEntity;
                    AnalysisPackage(entity, null);
                }
            });
        }
Ejemplo n.º 2
0
        private void ReceiveClients(object ChatClient)
        {
            ChatClient      u         = ChatClient as ChatClient;
            ObjectInversion inversion = new ObjectInversion();

            byte[] recvBytes = new byte[u.client.ReceiveBufferSize];
            while (true)  //注意,这里需要加个循环,否则之后client发送的数据无法接收
            {
                try
                {
                    u.stream.Read(recvBytes, 0, recvBytes.Length); //sync mode, 为什么一切换到async mode,就会发生乱序
                    ChatMessageEntity entity = inversion.DeSerializeTo(recvBytes) as ChatMessageEntity;
                    AnalysisPackage(entity, u);

                    //清空数组,以免脏读
                    recvBytes = new byte[u.client.ReceiveBufferSize];
                }
                catch { }
            }
        }