예제 #1
0
        private Message RecvSpecific(MessageCode code, int timeout = 5)
        {
            var startTime = DateTime.Now;

            while (true)
            {
                var msg = _client.RecvMessage();
                if (msg == null)
                {
                    if ((DateTime.Now - startTime).TotalSeconds > timeout)
                    {
                        _client.Close();
                        return(null);
                    }
                    Protocol.Yield();
                    continue;
                }
                if (msg.Code == code)
                {
                    return(msg);
                }
                else
                {
                    startTime = DateTime.Now;
                }
            }
        }
예제 #2
0
        public Message Recv()
        {
            var msg = _client.RecvMessage();

            if (msg == null)
            {
                if ((DateTime.Now - _lastInteraction).TotalMilliseconds > TIMEOUT)
                {
                    Send(new Message {
                        Code = MessageCode.PING
                    });
                }
            }
            else
            {
                Shake();
            }

            return(msg);
        }
예제 #3
0
        public void Listen()
        {
            try
            {
                TcpListener server = null;
                server = new TcpListener(IPAddress.Parse(_host), Protocol.TCP_PORT);

                server.Start();

                while (_flag.Retrieve((x) => x))
                {
                    if (!server.Pending())
                    {
                        Protocol.Yield();
                        continue;
                    }
                    var client = new ProtocolTcpClient();
                    client.Configure(server.AcceptTcpClient());
                    var message = client.RecvMessage();

                    if (message.Length > 0 && message.Code == MessageCode.CONNECT &&
                        Equals(Protocol.VERSION, message.GetReader().ReadString()))
                    {
                        var name = RandomNameGen.GetName();
                        Console.WriteLine("Connection: {0} => {1}", client.Address, name);
                        _clients.Act(x => x.Add(new UserTcpConnection(name, client)));
                    }
                    else
                    {
                        client.Close();
                    }
                }

                server.Stop();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }