예제 #1
0
        /// <summary>
        /// 网络集成测试
        /// </summary>
        public void NetworkIntergrateTest <T, V>(string connectStr)
            where T : INetworkServer, new()
            where V : INetworkClient, new()
        {
            //开启服务器
            INetworkServer server = NetworkFactory.CreateNetworkServer <T>();

            server.StartListen(connectStr);

            //测试用客户端进行连接
            INetworkClient client = null;

            ThreadPool.QueueUserWorkItem((o) => {
                Thread.Sleep(50); //假设50毫秒服务器可以开起来
                client = NetworkFactory.CreateNetworkClient <V>();
                client.Connect(connectStr);
            });

            //服务器获得新的session
            INetworkClientSession session = BlockWaitNewClient(server);

            Assert.IsNotNull(session);
            Assert.IsNotNull(client);
            Assert.IsTrue(client.Connected);

            //测试客户端往服务器发消息
            var testMsg = new GameMessage()
            {
                stateCode = 9999
            };

            client.Send(testMsg);
            var msg = BlockRead(session);

            Assert.AreEqual(msg.stateCode, 9999);

            //测试服务器往客户端发消息
            session.Send(new SyncMessage()
            {
                stateCode = 9993, timeleft = 3333
            });
            msg = BlockRead(client);
            Assert.IsTrue(msg is SyncMessage);
            Assert.AreEqual(msg.stateCode, 9993);
            Assert.AreEqual((msg as SyncMessage).timeleft, 3333);

            //关闭连接
            client.Close();
            Assert.IsFalse(client.Connected);
            session.Close();
            Assert.IsFalse(session.Connected);

            //关闭服务器
            server.Shutdown();
        }
예제 #2
0
        public void Start()
        {
            var listener = NetworkFactory.CreateNetworkServer <TcpNetworkServer>();

            listener.OnNewClient += (client) =>
            {
                GamePlayerSession session = new GamePlayerSession(client, this);
                //立刻读取请求
                //var msg = client.ReadSync();
                //if (msg != null && msg is ClientJoinMessage)
                //{
                //    var id = ((ClientJoinMessage)msg).id;
                //    this.NewPlayer(id, client);
                //}
                //else
                //{
                //    client.Close(); //非法传入,直接关闭
                //}
            };
            listener.StartListen(ConstSettings.DefaultServerEndPoint);

            //接收所有的客户端请求
            LoopFun();
        }