示例#1
0
        private void MainThread()
        {
            while (true)
            {
                Thread.Sleep(1);
                // Receiving
                NetworkStream stream = mainTc.GetStream();

                if (stream.CanRead && stream.DataAvailable)
                {
                    IFormatter       formatter  = new BinaryFormatter();
                    TCPServerMessage recvPacket = new TCPServerMessage();
                    recvPacket = (TCPServerMessage)formatter.Deserialize(stream);

                    if (recvPacket.Cmd == TCPServerCmd.PING)
                    {
                        TCPClientMessage sendPacket = new TCPClientMessage(recvPacket);
                        sendPacket.Cmd = TCPClientCmd.PONG;
                        formatter.Serialize(stream, sendPacket);
                    }
                    else if (recvPacket.Cmd == TCPServerCmd.Message)
                    {
                        string tmp_data = recvPacket.Param;
                        Debug.Print(tmp_data);
                        var json = JObject.Parse(tmp_data);

                        controller.ShowMessage(json["content"].ToString());
                    }
                }
                {
                    // Sending
                    if (this.sendQueue.Count == 0)
                    {
                        continue;
                    }
                    TCPClientMessage task = this.sendQueue.Dequeue();

                    IFormatter formatter = new BinaryFormatter();
                    task.RemoteTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
                    formatter.Serialize(stream, task);
                }
            }
        }
示例#2
0
        public void ping(TcpClient tc)
        {
            try
            {
                if (tc.GetStream().CanWrite)
                {
                    NetworkStream stream    = tc.GetStream();
                    IFormatter    formatter = new BinaryFormatter();

                    TCPServerMessage pck = new TCPServerMessage();
                    pck.Cmd   = TCPServerCmd.PING;
                    pck.Param = DateTimeOffset.Now.ToUnixTimeMilliseconds().ToString();
                    formatter.Serialize(stream, pck);
                }
            }
            catch (Exception)
            {
                CloseTcpClient(tc);
            }
        }
示例#3
0
 public TCPClientMessage(TCPServerMessage msg)
 {
     this.requestTime = msg.RequestTime;
 }