/// <summary> /// Setup everything required for this client to be accepted by the server and /// construct / send the connection header /// </summary> /// <param name="port">The port that was connected to on the remote host</param> protected virtual void Initialize(string host, ushort port) { // By default pending creates should be true and flushed when ready PendCreates = true; // Get a client stream for reading and writing. // Stream stream = client.GetStream(); // Get a random hash key that needs to be used for validating that the server was connected to headerHash = Websockets.HeaderHashKey(); // This is a typical Websockets accept header to be validated byte[] connectHeader = Websockets.ConnectionHeader(headerHash, port); // Send the accept headers to the server to validate RawWrite(connectHeader); // Setup the identity of the server as a player server = new NetworkingPlayer(0, host, true, client, this); //Let myself know I connected successfully OnPlayerConnected(server); // Set myself as a connected client server.Connected = true; }
protected void InitializeMasterClient(string host, ushort port) { // Get a client stream for reading and writing. // Stream stream = client.GetStream(); //获取需要用于验证服务器连接的随机哈希键 // Get a random hash key that needs to be used for validating that the server was connected to headerHash = Websockets.HeaderHashKey(); //这是一个典型的Websockets接受头被验证 // This is a typical Websockets accept header to be validated byte[] connectHeader = Websockets.ConnectionHeader(headerHash, port); //将接受标头发送到服务器进行验证 // Send the accept headers to the server to validate RawWrite(connectHeader); //将服务器的身份设置为玩家 // Setup the identity of the server as a player server = new NetworkingPlayer(0, host, true, client, this); //让我知道我连接成功 //Let myself know I connected successfully OnPlayerConnected(server); //将自己设置为连接的客户端 // Set myself as a connected client server.Connected = true; }
protected virtual void Initialize(string host, ushort port, bool pendCreates = true) { // By default pending creates should be true and flushed when ready if (pendCreates) { PendCreates = true; } // Get a random hash key that needs to be used for validating that the server was connected to headerHash = Websockets.HeaderHashKey(); // This is a typical Websockets accept header to be validated byte[] connectionHeader = Websockets.ConnectionHeader(headerHash, port); // Register the server as a NetworkingPlayer server = new NetworkingPlayer(0, host, true, client, this); // Send the upgrade request to the server RawWrite(connectionHeader); //Let myself know I connected successfully OnPlayerConnected(server); // Set myself as a connected client server.Connected = true; ReceiveToken token = new ReceiveToken { internalBuffer = new ArraySegment <byte>(buffer, 0, buffer.Length), player = server, bytesReceived = 0, dataHolder = null, maxAllowedBytes = 8192 }; // Read from the server async SocketAsyncEventArgs e = new SocketAsyncEventArgs(); e.Completed += new EventHandler <SocketAsyncEventArgs>(ReceiveAsync_Completed); e.UserToken = token; e.SetBuffer(token.internalBuffer.Array, token.internalBuffer.Offset, token.internalBuffer.Count); if (!client.Client.ReceiveAsync(e)) { Task.Queue(() => ReceiveAsync_Completed(this, e)); } }
private void SetNetworkBindings(ushort overrideBindingPort, ushort port, string natHost, string host, ushort natPort) { // Make sure not to listen on the same port as the server for local networks ushort clientPort = FindAvailablePort(overrideBindingPort, port); Client.EnableBroadcast = true; // If the server is behind a NAT, request for the port punch by the nat server if (!string.IsNullOrEmpty(natHost)) { nat.Connect(host, port, clientPort, natHost, natPort); } // Do any generic initialization in result of the successful bind OnBindSuccessful(); // Get a random hash key that needs to be used for validating that the server was connected to headerHash = Websockets.HeaderHashKey(); // Set the port SetPort(clientPort); }
/// <summary> /// This will connect a UDP client to a given UDP server /// </summary> /// <param name="host">The server's host address on the network</param> /// <param name="port">The port that the server is hosting on</param> /// <param name="natHost">The NAT server host address, if blank NAT will be skipped</param> /// <param name="natPort">The port that the NAT server is hosting on</param> /// <param name="pendCreates">Immidiately set the NetWorker::PendCreates to true</param> public void Connect(CSteamID hostId, bool pendCreates = false) { if (Disposed) { throw new ObjectDisposedException("UDPClient", "This object has been disposed and can not be used to connect, please use a new UDPClient"); } if (hostId.IsLobby()) { //If this is a lobby we need to join it, make direct connection to the owner. m_JoinCall = SteamMatchmaking.JoinLobby(hostId); m_LobbyEntered = Callback <LobbyEnter_t> .Create((LobbyEnter_t data) => { LobbyID = (CSteamID)data.m_ulSteamIDLobby; //Get the owner and attempt a direct connection Connect(SteamMatchmaking.GetLobbyOwner(LobbyID), pendCreates); }); return; } // By default pending creates should be true and flushed when ready if (!pendCreates) { PendCreates = true; } try { ushort clientPort = DEFAULT_PORT; // Make sure not to listen on the same port as the server for local networks if (clientPort == DEFAULT_PORT) { clientPort++; } Client = new CachedSteamP2PClient(hostId); // Do any generic initialization in result of the successful bind OnBindSuccessful(); // Get a random hash key that needs to be used for validating that the server was connected to headerHash = Websockets.HeaderHashKey(); // This is a typical Websockets accept header to be validated byte[] connectHeader = Websockets.ConnectionHeader(headerHash, DEFAULT_PORT); // Setup the identity of the server as a player server = new NetworkingPlayer(0, hostId, true, this); // Create the thread that will be listening for new data from connected clients and start its execution Task.Queue(ReadNetwork); //Let myself know I connected successfully OnPlayerConnected(server); // Set myself as a connected client server.Connected = true; //Set the port SetPort(clientPort); int connectCounter = 0; Task.Queue(() => { do { // Send the accept headers to the server to validate Client.Send(connectHeader, connectHeader.Length, hostId, EP2PSend.k_EP2PSendReliable); Thread.Sleep(3000); } while (!headerExchanged && IsBound && ++connectCounter < CONNECT_TRIES); if (connectCounter >= CONNECT_TRIES) { if (connectAttemptFailed != null) { connectAttemptFailed(this); } } }); m_CallbackP2PSessionConnectFail = Callback <P2PSessionConnectFail_t> .Create((P2PSessionConnectFail_t data) => { if (data.m_eP2PSessionError > 0) { Disconnect(true); switch (data.m_eP2PSessionError) { case 1: Logging.BMSLog.LogException("The target user is not running the same game."); break; case 2: Logging.BMSLog.LogException("The local user doesn't own the app that is running."); break; case 3: Logging.BMSLog.LogException("Target user isn't connected to Steam."); break; case 4: Logging.BMSLog.LogException("The connection timed out because the target user didn't respond, perhaps they aren't calling AcceptP2PSessionWithUser"); break; } } // }); } catch (Exception e) { Logging.BMSLog.LogException(e); // Do any generic initialization in result of the binding failure OnBindFailure(); throw new FailedBindingException("Failed to bind to host/port, see inner exception", e); } }
/// <summary> /// This will connect a UDP client to a given UDP server /// </summary> /// <param name="host">The server's host address on the network</param> /// <param name="port">The port that the server is hosting on</param> /// <param name="natHost">The NAT server host address, if blank NAT will be skipped</param> /// <param name="natPort">The port that the NAT server is hosting on</param> /// <param name="pendCreates">Immidiately set the NetWorker::PendCreates to true</param> public void Connect(string host, ushort port = DEFAULT_PORT, string natHost = "", ushort natPort = NatHolePunch.DEFAULT_NAT_SERVER_PORT, bool pendCreates = false, ushort overrideBindingPort = DEFAULT_PORT + 1) { if (Disposed) { throw new ObjectDisposedException("UDPClient", "This object has been disposed and can not be used to connect, please use a new UDPClient"); } // By default pending creates should be true and flushed when ready if (!pendCreates) { PendCreates = true; } try { ushort clientPort = overrideBindingPort; // Make sure not to listen on the same port as the server for local networks if (clientPort == port) { clientPort++; } for (; ; clientPort++) { try { Client = new CachedUdpClient(clientPort); break; } catch { if (port == 0) { throw new BaseNetworkException("There were no ports available starting from port " + port); } } } Client.EnableBroadcast = true; // If the server is behind a NAT, request for the port punch by the nat server if (!string.IsNullOrEmpty(natHost)) { nat.Connect(host, port, clientPort, natHost, natPort); } // Do any generic initialization in result of the successful bind OnBindSuccessful(); // Get a random hash key that needs to be used for validating that the server was connected to headerHash = Websockets.HeaderHashKey(); // This is a typical Websockets accept header to be validated byte[] connectHeader = Websockets.ConnectionHeader(headerHash, port); try { // Setup the identity of the server as a player server = new NetworkingPlayer(0, host, true, ResolveHost(host, port), this); } catch (ArgumentException) { if (connectAttemptFailed != null) { connectAttemptFailed(this); } throw; } // Create the thread that will be listening for new data from connected clients and start its execution Task.Queue(ReadNetwork); //Let myself know I connected successfully OnPlayerConnected(server); // Set myself as a connected client server.Connected = true; //Set the port SetPort(clientPort); int connectCounter = 0; Task.Queue(() => { do { // Send the accept headers to the server to validate Client.Send(connectHeader, connectHeader.Length, Server.IPEndPointHandle); Thread.Sleep(3000); } while (!headerExchanged && IsBound && ++connectCounter < CONNECT_TRIES); if (connectCounter >= CONNECT_TRIES) { if (connectAttemptFailed != null) { connectAttemptFailed(this); } } }); } catch (Exception e) { Logging.BMSLog.LogException(e); // Do any generic initialization in result of the binding failure OnBindFailure(); throw new FailedBindingException("Failed to bind to host/port, see inner exception", e); } }
/// <summary> /// Connect this FacepunchP2PClient directly to a steam user's FacepunchP2PServer with SteamId specified /// </summary> /// <param name="hostId">The host's <see cref="SteamId"/> SteamId object</param> /// <param name="pendCreates">Immediately set the NetWorker::PendCreates to true</param> public void Connect(SteamId hostId, bool pendCreates = false) { if (Disposed) { throw new ObjectDisposedException("FacepunchP2PClient", "This object has been disposed and can not be used to connect, please use a new FacepunchP2PClient"); } // By default pending creates should be true and flushed when ready if (!pendCreates) { PendCreates = true; } try { ushort clientPort = DEFAULT_PORT; // Make sure not to listen on the same port as the server for local networks if (clientPort == DEFAULT_PORT) { clientPort++; } Client = new CachedFacepunchP2PClient(hostId); // Do any generic initialization in result of the successful bind OnBindSuccessful(); // Get a random hash key that needs to be used for validating that the server was connected to headerHash = Websockets.HeaderHashKey(); // This is a typical Websockets accept header to be validated byte[] connectHeader = Websockets.ConnectionHeader(headerHash, DEFAULT_PORT); // Setup the identity of the server as a player server = new NetworkingPlayer(0, hostId, true, this); // Create the thread that will be listening for new data from connected clients and start its execution Task.Queue(ReadNetwork); //Let myself know I connected successfully OnPlayerConnected(server); // Set myself as a connected client server.Connected = true; //Set the port SetPort(clientPort); int connectCounter = 0; Task.Queue(() => { do { // Send the accept headers to the server to validate Client.Send(connectHeader, connectHeader.Length, hostId, P2PSend.Reliable); Thread.Sleep(3000); } while (!headerExchanged && IsBound && ++connectCounter < CONNECT_TRIES); if (connectCounter >= CONNECT_TRIES) { if (connectAttemptFailed != null) { connectAttemptFailed(this); } } }); } catch (Exception e) { Logging.BMSLog.LogException(e); // Do any generic initialization in result of the binding failure OnBindFailure(); throw new FailedBindingException("Failed to bind to server's SteamId, see inner exception", e); } }
public void Connect(string host, ushort port = DEFAULT_PORT, string natHost = "", ushort natPort = NatHolePunch.DEFAULT_NAT_SERVER_PORT, bool isSpecial = false) { // By default pending creates should be true and flushed when ready if (!isSpecial) { PendCreates = true; } try { // TODO: Remove + 1, it is for linux tests ushort clientPort = port; //(ushort)(port + 1); for (; ; clientPort++) { try { Client = new CachedUdpClient(clientPort); break; } catch { if (port == 0) { throw new BaseNetworkException("There were no ports available starting from port " + port); } } } Client.EnableBroadcast = true; // If the server is behind a NAT, request for the port punch by the nat server if (!string.IsNullOrEmpty(natHost)) { nat.Connect(host, port, clientPort, natHost, natPort); } // Do any generic initialization in result of the successful bind OnBindSuccessful(); // Get a random hash key that needs to be used for validating that the server was connected to headerHash = Websockets.HeaderHashKey(); // This is a typical Websockets accept header to be validated byte[] connectHeader = Websockets.ConnectionHeader(headerHash, port); // Setup the identity of the server as a player server = new NetworkingPlayer(0, host, true, ResolveHost(host, port), this); // Create the thread that will be listening for new data from connected clients and start its execution Task.Queue(ReadNetwork); //Let myself know I connected successfully OnPlayerConnected(server); // Set myself as a connected client server.Connected = true; //Set the port SetPort(clientPort); Task.Queue(() => { do { // Send the accept headers to the server to validate Client.Send(connectHeader, connectHeader.Length, Server.IPEndPointHandle); Thread.Sleep(3000); } while (!headerExchanged && IsBound); }); } catch (Exception e) { Logging.BMSLog.LogException(e); // Do any generic initialization in result of the binding failure OnBindFailure(); throw new FailedBindingException("Failed to bind to host/port, see inner exception", e); } }