Ejemplo n.º 1
0
        public bool Connect(bool bTcp, string ip, ushort port, uint newip = 0, ushort newport = 0)
        {
            Debug.Log("连接到服务器 IP = " + ip);
            if (tCPClient != null && tCPClient.IsConnected)
            {
                Debug.Log("TCP is connected.");
                return(false);
            }
            INetClient tt;
            bool       bret = true;

            if (bTcp)
            {
                tt   = new TCPClient(this);
                bret = tt.Connect(ip, port);
            }
            else
            {
                tt   = new UDPClient(this);
                bret = tt.Connect(ip, port);
                //tt = new UDPClient(this);
                //bret = tt.Connect(ip, port, newip, newport);
            }

            tCPClient = tt;
            return(bret);
        }
Ejemplo n.º 2
0
		public async void UDPTryConnect()
		{
			ILog rsp = UDPRemoteEndPoint.Initialize();
			if (rsp != null)
			{
				rsp.Print();
				return;
			}

			udpClient = new UDPClient(SimulationClient, UDPRemoteEndPoint.LocalPort, UDPRemoteEndPoint, UDPClientState, ContextHandler);
			Debug.Log("[UDP] Connecting");

			// this blocks but the main thread still goes on so Unity continues as normal
			rsp = await udpClient.Connect();
			if (rsp != null)
			{
				rsp.Print();
				return;
			}
			Debug.Log("[UDP] Connected");

			rsp = await udpClient.Listen();
			if (rsp != null)
			{
				rsp.Print();
				return;
			}
			Debug.Log("[UDP] Disconnected");
		}
Ejemplo n.º 3
0
    public void ConnectToServer()
    {
        if (bConnected)
        {
            return;
        }

        client = new UDPClient();
        //client.SetUserAuthenticator(this);
        client.serverAccepted       += OnAccepted;
        client.connectAttemptFailed += Client_connectAttemptFailed;
        client.disconnected         += Client_disconnected;
        client.Connect(hostAddress, port);
        bConnected = true;

        if (!client.IsBound)
        {
            Debug.LogError("NetWorker failed to bind");
            return;
        }

        if (mgr == null)
        {
            mgr = Instantiate(networkManagerPrefab).GetComponent <NetworkManager>();
        }

        mgr.Initialize(client, masterServerHost, masterServerPort);
    }
Ejemplo n.º 4
0
    public bool Connect(bool bTCP, string ip, ushort port, uint newip = 0, ushort newport = 0)
    {
        if (m_TCPClient != null && m_TCPClient.IsConnected)
        {
            LogMgr.Log("TCP is connected.");
            return(false);
        }
        INetClient tt;
        //bTCP = true;
        bool bret;

        if (bTCP)
        {
            tt   = new TCPClient(this);
            bret = tt.Connect(ip, port, newip, newport);
        }
        else
        {
            tt   = new UDPClient(this);
            bret = tt.Connect(ip, port, newip, newport);
        }

        m_TCPClient = tt;
        return(bret);
    }
Ejemplo n.º 5
0
        void testUDP()
        {
            Debug.Log("测试 UDP Client");

            UDPClient client = new UDPClient();

            client.OnNetworkStateChanged += (state, err) => {
                Debug.Log("UDP 网络状态改变:" + state + err);
            };

            IPAddress ipAddress = IPAddress.Parse("127.0.0.1");

            client.Connect(ipAddress, 9001, () => {
                Debug.Log("UDP连接成功");

                client.Request("game.join", "helloUDP".StringToBytes(), (c, r) => {
                    var msg = r.BytesToString();
                    Console.WriteLine("收到:{0}, {1}", c, msg);
                });

                client.Request("game.login", "login".StringToBytes(), (c, r) => {
                    var msg = r.BytesToString();
                    Console.WriteLine("收到:{0}, {1}", c, msg);
                });
                int eid = 0;
                eid     = client.AddEvent("game.push", (r) => {
                    var msg = r.BytesToString();
                    if (msg == "推送消息 3")
                    {
                        client.RemoveEvent(eid);
                    }
                    Console.WriteLine("收到推送的数据:{0}", msg);
                });
            });
        }
Ejemplo n.º 6
0
        protected override void Initialize()
        {
            _graphics.PreferredBackBufferWidth  = windowWidth;
            _graphics.PreferredBackBufferHeight = windowHeight;
            _graphics.IsFullScreen = false;
            _graphics.ApplyChanges();

            nMap = NewMap.Load(@"..\..\..\MapData\Map2.1.tmx");
            //nMap = NewMap.Load(@"..\..\..\MapData\Map.tmx");
            // map = new Map(@"..\..\..\MapData\Map2.tmx", @"..\..\..\MapData\GrassTileset.tsx", Content);

            allPlayers = new Dictionary <int, Player>();
            player     = new Player(nMap.playerStart, "Conjurer", Content);

            //camera = new Camera(GraphicsDevice.Viewport);

            nCamera        = new NewCamera(GraphicsDevice.Viewport);
            nCamera.Limits = new Rectangle(0, 0, nMap._width * nMap.tileset._tileWidth, nMap._height * nMap.tileset._tileHeight);

            client = new UDPClient();
            if (!client.Connect("79.114.16.172", 5555))
            {
                Console.WriteLine("Cannot connect to server!");

                // Exit();
            }

            player.ID = client.ClientID;
            client.SendMessageExceptOne(player.toPlayerInfo(), player.ID);

            allPlayers.Add(player.ID, player);

            base.Initialize();
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Connect to the NAT hole punch server, this is called from a client machine
        /// </summary>
        /// <param name="host">The host address of the server the client is trying to connect to</param>
        /// <param name="port">The port number of the server the client is trying to connect to</param>
        /// <param name="clientPort">The port number that the client is listening on</param>
        /// <param name="natServer">The NAT server host address to connect to</param>
        /// <param name="natPort">The NAT server port number to connect to</param>
        public void Connect(string host, ushort port, ushort clientPort, string natServer,
                            ushort natPort = DEFAULT_NAT_SERVER_PORT)
        {
            // Don't allow multiple NAT server connection requests at once
            if (Client != null)
            {
                return;
            }

            // Connect to the NAT server
            Client = new UDPClient();
            Client.Connect(natServer, natPort, pendCreates: true);

            NetWorker.BaseNetworkEvent accepted = (NetWorker sender) => {
                // Send the data to the nat server with the host address and port that this client
                // is trying to connect to so that it can punch a hole in the network for this client
                JSONNode sendJson = JSONNode.Parse("{}");
                sendJson.Add("host", new JSONData(host));
                sendJson.Add("port", new JSONData(port));
                sendJson.Add("clientPort", new JSONData(clientPort));

                // Send the message to the NAT server
                Text connect = Text.CreateFromString(Client.Time.Timestep, sendJson.ToString(), false, Receivers.Server,
                                                     MessageGroupIds.NAT_SERVER_CONNECT, false);
                Client.Send(connect, true);
                Client.messageConfirmed += (player, packet) => {
                    if (packet.uniqueId == connect.UniqueId)
                    {
                        Client.Disconnect(false);
                    }
                };
            };

            Client.serverAccepted += accepted;
        }
Ejemplo n.º 8
0
        public void ServerReceiving(double packetLoss)
        {
            UDPSocket.PACKET_LOSS = packetLoss;

            UDPServer server = GetServer();

            uint expected = 0;

            server.OnData += (ep, data) =>
            {
                uint num = BitConverter.ToUInt32(data, 0);

                Assert.AreEqual(expected++, num);
            };

            server.Start();

            UDPClient client = GetClient();

            client.Connect();

            for (uint i = 0; i < 10000; i++)
            {
                byte[] data = BitConverter.GetBytes(i);
                client.Send(data);
                Thread.Sleep(0);
            }

            Thread.Sleep(1000);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Registers a server to the NAT server so that it can be requested to be joined by clients
        /// </summary>
        /// <param name="currentPort">The current port that this server is listening for client connections on</param>
        /// <param name="natServer">The NAT server host address to connect to</param>
        /// <param name="natPort">The NAT server port number to connect to</param>
        public void Register(ushort currentPort, string natServer, ushort natPort = DEFAULT_NAT_SERVER_PORT)
        {
            // Don't allow multiple NAT server connection requests at once
            if (Client != null)
            {
                return;
            }

            // Connect to the NAT server
            Client = new UDPClient();
            Client.Connect(natServer, natPort, pendCreates: true);

            // When connected, request for this server to be registered to the NAT lookup for clients
            NetWorker.BaseNetworkEvent accepted = (NetWorker sender) => {
                JSONNode obj = JSONNode.Parse("{}");
                obj.Add("port", new JSONData(currentPort));

                JSONClass sendJson = new JSONClass();
                sendJson.Add("register", obj);

                // Send the message to the NAT server
                Text register = Text.CreateFromString(Client.Time.Timestep, sendJson.ToString(), false,
                                                      Receivers.Target, MessageGroupIds.NAT_SERVER_REGISTER, false);
                Client.Send(register, true);
            };

            Client.serverAccepted += accepted;

            // Setup the callback events for when clients attempt to join
            Client.textMessageReceived += PlayerConnectRequestReceived;
        }
Ejemplo n.º 10
0
        public void BidirectionalReceiving(double packetLoss)
        {
            UDPSocket.PACKET_LOSS = packetLoss;

            UDPServer <TestBehavior> server = GetServer <TestBehavior>();

            server.Start();

            UDPClient client = GetClient();

            uint expected = 0;

            client.OnMessage += (s, d) =>
            {
                uint num = BitConverter.ToUInt32(d.Data, 0);
                Assert.AreEqual(expected++, num);
            };

            client.Connect();

            for (uint i = 0; i < 10000; i++)
            {
                byte[] data = BitConverter.GetBytes(i);
                client.Send(data);
            }

            Thread.Sleep(1000);
        }
        protected static void ConnectSetup(bool useOtherClient = false, NetworkObject.NetworkObjectEvent objectCreatedCallback = null)
        {
            currentPort = GetPort();
            start       = DateTime.UtcNow;

            server = new UDPServer(32);
            server.Connect(port: currentPort);

            if (objectCreatedCallback != null)
            {
                server.objectCreated += objectCreatedCallback;
            }

            client = new UDPClient();
            client.Connect("127.0.0.1", currentPort);

            if (objectCreatedCallback != null)
            {
                client.objectCreated += objectCreatedCallback;
            }

            WaitFor(() => { return(server.Players.Last().Accepted); });
            NetworkObject.Flush(client);

            if (!useOtherClient)
            {
                return;
            }

            OtherClientConnectSetup(objectCreatedCallback);
        }
    public void ConnectToMatchmaking()
    {
        if (_matchmaking)
        {
            return;
        }

        SetToggledButtons(false);
        _matchmaking = true;

        if (mgr == null && networkManager == null)
        {
            throw new System.Exception("A network manager was not provided, this is required for the tons of fancy stuff");
        }

        mgr = Instantiate(networkManager).GetComponent <NetworkManager>();

        mgr.MatchmakingServersFromMasterServer(masterServerHost, masterServerPort, myElo, (response) =>
        {
            _matchmaking = false;
            SetToggledButtons(true);
            Debug.LogFormat("Matching Server(s) count[{0}]", response.serverResponse.Count);

            //TODO: YOUR OWN MATCHMAKING EXTRA LOGIC HERE!
            // I just make it randomly pick a server... you can do whatever you please!
            if (response != null && response.serverResponse.Count > 0)
            {
                MasterServerResponse.Server server = response.serverResponse[Random.Range(0, response.serverResponse.Count)];
                //TCPClient client = new TCPClient();
                UDPClient client = new UDPClient();
                client.Connect(server.Address, server.Port);
                Connected(client);
            }
        });
    }
Ejemplo n.º 13
0
    public void Connect()
    {
        var client = new UDPClient();

        client.Connect(ipAdressInput.text, ushort.Parse(portInput.text));

        networkManager.Initialize(client);
    }
        protected static void OtherClientConnectSetup(NetworkObject.NetworkObjectEvent objectCreatedCallback = null)
        {
            otherClient = new UDPClient();
            otherClient.Connect("127.0.0.1", currentPort);

            if (objectCreatedCallback != null)
            {
                otherClient.objectCreated += objectCreatedCallback;
            }

            WaitFor(() => { return(server.Players.Last().Accepted); });
            NetworkObject.Flush(otherClient);
        }
Ejemplo n.º 15
0
        public void ConnectTest()
        {
            client = new UDPClient();

            Console.WriteLine("Using port number: " + currentPort);
            client.Connect("127.0.0.1", currentPort);
            Assert.IsTrue(client.IsBound);
            WaitFor(() => { return(client.IsConnected); });

            client.Disconnect(false);

            WaitFor(() => { return(!client.IsConnected); });
            Assert.IsFalse(client.IsBound);
        }
Ejemplo n.º 16
0
    private void Client_ConnectToServer(ServerInfo hostInfo)
    {
        UDPClient udpClient = new UDPClient();

        udpClient.Connect(hostInfo.ip, hostInfo.port);
        _myNetWorker = udpClient;

        OnConnectionMade(udpClient);
        IsCurrentlyConnectingToServer = true;
        ServerCurrentlyConnectedTo    = hostInfo;

        udpClient.disconnected         += Client_OnDisconnected;
        udpClient.serverAccepted       += Client_OnConnectionSuccess;
        udpClient.connectAttemptFailed += Client_OnConnectionFailure;

        Client_ConnectionToServerAttempted?.Invoke();
    }
Ejemplo n.º 17
0
        protected override void Run()
        {
            Client.Connect();

            while (IsRunning)
            {
                try
                {
                    Network data = Client.ReceiveData <Network>();
                    if (data == null)
                    {
                        continue;
                    }

                    Network = data;
                    CalculatePosition();
                }
                catch (ServerStoppedRespondingException)
                {
                    Console.WriteLine("Lost connection, trying to reconnect");
                    if (!Client.ReConnect())
                    {
                        Stop();
                        return;
                    }
                }
                catch (ServerStoppingException)
                {
                    Console.WriteLine("Server closing, trying to reconnect");
                    if (!Client.ReConnect())
                    {
                        Stop();
                        return;
                    }
                }
                catch (NoAcknowledgementException)
                {
                    Console.WriteLine("Server did not acknowledge client, trying to reconnect");
                    if (!Client.ReConnect())
                    {
                        Stop();
                        return;
                    }
                }
            }
        }
Ejemplo n.º 18
0
        protected override void Run()
        {
            Client.Connect();

            while (IsRunning)
            {
                try
                {
                    Sensors data = Client.ReceiveData <Sensors>();

                    if (data != null)
                    {
                        Sensors  = data;
                        Response = new Response(true, CalculatePosition(), 75);
                    }
                }
                catch (ServerStoppedRespondingException)
                {
                    Console.WriteLine("Lost connection, trying to reconnect");
                    if (!Client.ReConnect())
                    {
                        Stop();
                        return;
                    }
                }
                catch (ServerStoppingException)
                {
                    Console.WriteLine("Server closing, trying to reconnect");
                    if (!Client.ReConnect())
                    {
                        Stop();
                        return;
                    }
                }
                catch (NoAcknowledgementException)
                {
                    Console.WriteLine("Server did not acknowledge client, trying to reconnect");
                    if (!Client.ReConnect())
                    {
                        Stop();
                        return;
                    }
                }
            }
        }
Ejemplo n.º 19
0
        public void MultipleReconnectTest()
        {
            UDPClient singleClient;
            int       i, clientCount = 4;

            for (i = 0; i < clientCount; i++)
            {
                singleClient = new UDPClient();
                singleClient.Connect("127.0.0.1", currentPort);
                Assert.IsTrue(singleClient.IsBound);
                WaitFor(() => { return(singleClient.IsConnected); });
                singleClient.Disconnect(false);
                WaitFor(() => { return(!singleClient.IsConnected); });
                Assert.IsFalse(singleClient.IsBound);
                singleClient = null;
                WaitFor(() => { return(server.Players.Count == 1); });
            }
        }
Ejemplo n.º 20
0
        public void ServerBehaviorReceiving(double packetLoss)
        {
            UDPSocket.PACKET_LOSS = packetLoss;

            UDPServer <TestBehavior> server = GetServer <TestBehavior>();

            server.Start();

            UDPClient client = GetClient();

            client.Connect();

            for (uint i = 0; i < 10000; i++)
            {
                byte[] data = BitConverter.GetBytes(i);
                client.Send(data);
            }

            Thread.Sleep(1000);
        }
    void Start()
    {
        if (IsServer)
        {
            m_Server = new UDPServer(2);
            m_Server.binaryMessageReceived += ServerOnBinaryMessageReceived;
            NetworkManager.Instance.Initialize(m_Server);
            m_Server.Connect(m_Ip, m_Port);
        }
        else
        {
            m_Client = new UDPClient();
            m_Client.binaryMessageReceived += ClientOnBinaryMessageReceived;
            NetworkManager.Instance.Initialize(m_Client);
            m_Client.Connect(m_Ip, m_Port);
        }

        m_Player1             = GameObject.Find("p1");
        m_Player1PrevPosition = m_Player1.transform.position;
    }
Ejemplo n.º 22
0
        // Connect to the time server
        public void Connect()
        {
            try {
                IPAddress  hostadd = DNS.Resolve(TimeServer);
                IPEndPoint EPhost  = new IPEndPoint(hostadd, 123);

                UDPClient TimeSocket = new UDPClient();
                TimeSocket.Connect(EPhost);
                Initialize();
                TimeSocket.Send(NTPData, NTPData.Length);
                NTPData = TimeSocket.Receive(ref EPhost);
                if (!IsResponseValid())
                {
                    throw new Exception("Invalid response from " + TimeServer);
                }
                ReceptionTimestamp = DateTime.Now;
            } catch (SocketException e)
            {
                throw new Exception(e.Message);
            }
        }
Ejemplo n.º 23
0
 public void Connect()
 {
     client = new UDPClient();
     client.Connect(ip, port);
     Connected(client);
 }
Ejemplo n.º 24
0
 public void Connect()
 {
     Debug.Assert(peerId == 0 && Connecting == false && Connected == false);
     cli.Connect("127.0.0.1", 1234);
 }
Ejemplo n.º 25
0
 /// <summary>
 /// Sets the client as a sender to address:port
 /// </summary>
 /// <returns>UdpClientHelper.</returns>
 /// <param name="address">Remote DNS or IP address.</param>
 /// <param name="port">port to send to</param>
 public UdpClientHelper Sender(string address, int port)
 {
     udpClient.Connect(address, port);
     return(this);
 }
Ejemplo n.º 26
0
 public void Connect_Disconnect()
 {
     client.Connect();
     client.Disconnect();
 }