public void StartClient() { OnApplicationQuit(); client = RakPeerInterface.GetInstance(); SocketDescriptor socketDescriptor = new SocketDescriptor(Convert.ToUInt16(UnityEngine.Random.Range(81, 65536)), "0"); socketDescriptor.socketFamily = 2; client.Startup(8, socketDescriptor, 1); client.SetOccasionalPing(true); ConnectionAttemptResult car = client.Connect(input_IP.text, Convert.ToUInt16(input_PORT.text), "Rumpelstiltskin", "Rumpelstiltskin".Length); if (car != RakNet.ConnectionAttemptResult.CONNECTION_ATTEMPT_STARTED) { Debug.LogError(car); } Debug.LogWarning("My IP Addresses:"); for (uint i = 0; i < client.GetNumberOfAddresses(); i++) { Debug.LogWarning(client.GetLocalIP(i).ToString()); } Debug.LogWarning("My GUID is " + client.GetGuidFromSystemAddress(RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS).ToString()); }
IEnumerator connectToNATFacilitatorTest() { StartupResult startResult = rakPeerTest.Startup(2, new SocketDescriptor(), 1); if (startResult != StartupResult.RAKNET_STARTED) { Debug.Log("Failed to initialize network interface 2: " + startResult.ToString()); yield break; } ConnectionAttemptResult connectResult = rakPeerTest.Connect(facilitatorIP, (ushort)facilitatorPort, null, 0); if (connectResult != ConnectionAttemptResult.CONNECTION_ATTEMPT_STARTED) { Debug.Log("Failed to initialize connection to NAT Facilitator 2: " + connectResult.ToString()); yield break; } Packet packet; while ((packet = rakPeerTest.Receive()) == null) { yield return(new WaitForEndOfFrame()); } if (packet.data[0] != (byte)DefaultMessageIDTypes.ID_CONNECTION_REQUEST_ACCEPTED) { Debug.Log("Failed to connect to NAT Facilitator 2: " + ((DefaultMessageIDTypes)packet.data[0])); yield break; } guidTest = rakPeerTest.GetMyGUID().g.ToString(); Debug.Log("Connected 2: " + guidTest); facilitatorSystemAddressTest = packet.systemAddress; externalIP = rakPeerTest.GetExternalID(packet.systemAddress).ToString(false); rakPeerTest.SetMaximumIncomingConnections(2); if (firstTimeConnectTest) { firstTimeConnectTest = false; natPunchthroughClientTest = new NatPunchthroughClient(); rakPeerTest.AttachPlugin(natPunchthroughClientTest); natPunchthroughClientTest.FindRouterPortStride(facilitatorSystemAddressTest); } else { StartCoroutine("waitForIncomingNATPunchThroughOnServerTest"); } connectedToFacTest = true; isReadyTest = true; }
/// <summary> /// Connecting to the server by IP address, specifying the password for connection and connection attempts (All connection errors will be returned by the OnDisconnected method) /// </summary> public ConnectionAttemptResult Connect(string address, ushort port, string password = "", short attempts = 20) { ConnectionAttemptResult result = peer.StartClient(address, port, password, attempts); if (result == ConnectionAttemptResult.CONNECTION_ATTEMPT_STARTED) { IsConnecting = true; IsConnected = false; OnConnecting(address, port, password); } return(result); }
public ConnectionAttemptResult StartClient(string address, ushort port, string password = "", short attempts = 10) { if (pointer == IntPtr.Zero) { return(ConnectionAttemptResult.INVALID_CONNECT_PARAMETER); } ConnectionAttemptResult = RakPeer_Native.NET_StartClient(pointer, address, port, password, attempts); if (ConnectionAttemptResult == ConnectionAttemptResult.CONNECTION_ATTEMPT_STARTED) { Type = PeerType.Client; is_shutteddown = false; } return(ConnectionAttemptResult); }
/// <summary> /// 开启网络连接 /// </summary> public void Connect(string serverIP, ushort serverPort, Action <bool> connectCallBack) { if (IsConnectedServer || IsConnecting) // 已经连接上了服务器 { Debug.LogErrorFormat("已经连接上了服务器,请勿重复链接 0:{0} 1:{1} IP:{2} Port:{3}", IsConnectedServer, IsConnecting, serverIP, serverPort); connectCallBack(false); return; } if (!IsStartUp) { Debug.LogError("连接时,没有初始化raknet"); connectCallBack(false); return; } this.ServerIP = serverIP; this.ServerPort = serverPort; if (!IsValidity()) { Debug.LogErrorFormat("Cann't connect client[{0}], it have some error of server ip[{1}] or server port[{2}], please check it!", this.ClientName, this.ServerIP, this.ServerPort); connectCallBack(false); return; } this.connectCallBack = connectCallBack; //Debug.Log(string.Format("调用raknet连接接口 serverip{0}, port{1}", this.ServerIP, this.ServerPort)); ConnectionAttemptResult connectResult = mClient.Connect(this.ServerIP, this.ServerPort, null, 0); //Debug.Log("调用连接接口的返回值 = " + connectResult); if (connectResult == ConnectionAttemptResult.CONNECTION_ATTEMPT_STARTED) { IsConnecting = true; //IsConnectSuccess = false; //// 已经向服务器发送了连接请求,等待服务器消息反馈 //// 真正连接成功需要等待服务器返回消息才知道连接成功与否 } else { IsConnecting = false; connectCallBack(false); } }
public bool Connect(string ip, int port, string pwd) { m_Socket = RakPeerInterface.GetInstance(); m_Socket.AllowConnectionResponseIPMigration(false); SocketDescriptor socketDescriptor = new SocketDescriptor(0, "0"); socketDescriptor.socketFamily = 2; m_Socket.Startup(8, socketDescriptor, 1); m_Socket.SetOccasionalPing(true); ConnectionAttemptResult car = m_Socket.Connect(ip, (ushort)port, pwd, pwd.Length); if (car == ConnectionAttemptResult.CONNECTION_ATTEMPT_STARTED) { return(true); } else { m_Socket.Shutdown(300); RakPeerInterface.DestroyInstance(m_Socket); return(false); } }
public int Start(string ip, ushort port) { this.client = RakPeer.GetInstance(); SocketDescriptor socketDescriptor = new SocketDescriptor(); socketDescriptor.socketFamily = 2; StartupResult result = this.client.Startup(1, socketDescriptor, 1); if (result != StartupResult.RAKNET_STARTED) { string str = string.Format("客户端启动失败 retCode:{0}", result); Log.WriteLine(str); return(-1); } ConnectionAttemptResult connResult = this.client.Connect(ip, port, "", 0); if (connResult != ConnectionAttemptResult.CONNECTION_ATTEMPT_STARTED) { string str = string.Format("连接失败 retCode:{0}", result); Log.WriteLine(str); return(-2); } begin = Time.time + SEND_INTERVAL; // remote target this.remote = new SystemAddress(ip, port); // send data this.data = new RakNet.BitStream(); this.data.Reset(); this.data.Write((byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM); this.data.Write("hello world!"); return(0); }
public void Start() { InitPeer(); if (_State == RakNetClientState.PeerInitOK) { StartupResult result = _peer.Startup(1, _socketDesc, 1); Log.Debug("Start Result: " + result); if (result == StartupResult.RAKNET_STARTED) { _State = RakNetClientState.StartUpOK; RakNet.FT_ConnectProcess process = new RakNet.FT_ConnectProcess(); process.SetResultHandler(new RakNetClientResultHandler(this)); AttachInterface2(process); ConnectionAttemptResult connectResult = _peer.Connect(_sServerIP, _nServerPort, "", 0); Log.Debug("Connect Result: " + connectResult); if (ConnectionAttemptResult.CONNECTION_ATTEMPT_STARTED == connectResult) { _State = RakNetClientState.ConnectOK; _systemAddress = new SystemAddress(_sServerIP, _nServerPort); _ReadThread.Start(); } else { _State = RakNetClientState.ConnectError; } } else { Log.Debug("RakNet.RakPeerInterface.GetInstance() Error : " + result); _State = RakNetClientState.StartUpError; } } }
internal static void Connect() { try { if (isConnected || isConnecting) { return; } isConnecting = true; ConnectionAttemptResult res = clientInterface.Connect(Program.ServerIP, Program.ServerPort, Program.Password, Program.Password == null ? 0 : Program.Password.Length); if (res != ConnectionAttemptResult.CONNECTION_ATTEMPT_STARTED) { throw new Exception("Connection couldn't be established: " + res); } Logger.Log("Connection attempt {0} to '{1}:{2}' started.", ++connectionAttempts, Program.ServerIP, Program.ServerPort); } catch (Exception e) { Logger.LogError("Connection failed! " + e); } }
IEnumerator connectToNATFacilitator() { StartupResult startResult = rakPeer.Startup(2, new SocketDescriptor(), 1); if (startResult != StartupResult.RAKNET_STARTED) { NATNetworkManager_PHP.DisplayLog("Failed to initialize network interface: " + startResult.ToString()); yield break; } ConnectionAttemptResult connectResult = rakPeer.Connect(facilitatorIP, (ushort)facilitatorPort, null, 0); if (connectResult != ConnectionAttemptResult.CONNECTION_ATTEMPT_STARTED) { NATNetworkManager_PHP.DisplayLog("Failed to initialize connection to NAT Facilitator: " + connectResult.ToString()); yield break; } Packet packet; while ((packet = rakPeer.Receive()) == null) { yield return(new WaitForEndOfFrame()); } if (packet.data[0] != (byte)DefaultMessageIDTypes.ID_CONNECTION_REQUEST_ACCEPTED) { NATNetworkManager_PHP.DisplayLog("Failed to connect to NAT Facilitator: " + ((DefaultMessageIDTypes)packet.data[0])); NATNetworkManager_PHP.RefreshInfo(); yield break; } guid = rakPeer.GetMyGUID().g.ToString(); Debug.Log("Connected: " + guid); externalIP = rakPeer.GetExternalID(packet.systemAddress).ToString(false); NATNetworkManager_PHP.RefreshInfo(); //if (firstTimeConnect) { // firstTimeConnect = false; natPunchthroughClient = new NatPunchthroughClient(); rakPeer.AttachPlugin(natPunchthroughClient); natPunchthroughClient.FindRouterPortStride(packet.systemAddress); facilitatorSystemAddress = packet.systemAddress; /*} else { * rakPeer.AttachPlugin (natPunchthroughClient); * //if (!facilitatorSystemAddress.EqualsExcludingPort(packet.systemAddress)) { * natPunchthroughClient.FindRouterPortStride (packet.systemAddress); * //} * facilitatorSystemAddress = packet.systemAddress; * }*/ if (NetworkServer.active && NATNetworkManager_PHP.singleton.myRoom.isNetGame) { StartCoroutine("waitForIncomingNATPunchThroughOnServer"); } if (string.IsNullOrEmpty(guid)) { NATNetworkManager_PHP.DisplayLog("GUID IS NULL OR EMPTY"); } else { NATNetworkManager_PHP.singleton.StartCoroutine("setNewGUID", guid); } NATNetworkManager_PHP.connectedToFac = true; rakPeer.SetMaximumIncomingConnections(2); isReady = true; }
public virtual ConnectionAttemptResult Connect(string host, ushort remotePort, string passwordData, int passwordDataLength, PublicKey publicKey, uint connectionSocketIndex) { ConnectionAttemptResult ret = (ConnectionAttemptResult)RakNetPINVOKE.RakPeerInterface_Connect__SWIG_3(swigCPtr, host, remotePort, passwordData, passwordDataLength, PublicKey.getCPtr(publicKey), connectionSocketIndex); return(ret); }
public virtual ConnectionAttemptResult Connect(string host, ushort remotePort, string passwordData, int passwordDataLength) { ConnectionAttemptResult ret = (ConnectionAttemptResult)RakNetPINVOKE.RakPeerInterface_Connect__SWIG_5(swigCPtr, host, remotePort, passwordData, passwordDataLength); return(ret); }
public virtual ConnectionAttemptResult Connect(string host, ushort remotePort, string passwordData, int passwordDataLength, PublicKey publicKey, uint connectionSocketIndex, uint sendConnectionAttemptCount, uint timeBetweenSendConnectionAttemptsMS, uint timeoutTime) { ConnectionAttemptResult ret = (ConnectionAttemptResult)RakNetPINVOKE.RakPeerInterface_Connect__SWIG_0(swigCPtr, host, remotePort, passwordData, passwordDataLength, PublicKey.getCPtr(publicKey), connectionSocketIndex, sendConnectionAttemptCount, timeBetweenSendConnectionAttemptsMS, timeoutTime); return(ret); }
public override ConnectionAttemptResult Connect(string host, ushort remotePort, string passwordData, int passwordDataLength, PublicKey publicKey) { ConnectionAttemptResult ret = (ConnectionAttemptResult)RakNetPINVOKE.RakPeer_Connect__SWIG_4(swigCPtr, host, remotePort, passwordData, passwordDataLength, PublicKey.getCPtr(publicKey)); return(ret); }
public override ConnectionAttemptResult Connect(string host, ushort remotePort, string passwordData, int passwordDataLength, PublicKey publicKey, uint connectionSocketIndex, uint sendConnectionAttemptCount) { ConnectionAttemptResult ret = (ConnectionAttemptResult)RakNetPINVOKE.RakPeer_Connect__SWIG_2(swigCPtr, host, remotePort, passwordData, passwordDataLength, PublicKey.getCPtr(publicKey), connectionSocketIndex, sendConnectionAttemptCount); return(ret); }
public override ConnectionAttemptResult Connect(string host, ushort remotePort, string passwordData, int passwordDataLength) { ConnectionAttemptResult ret = (ConnectionAttemptResult)RakNetPINVOKE.CSharp_RakPeer_Connect__SWIG_5(swigCPtr, host, remotePort, passwordData, passwordDataLength); return(ret); }
public virtual ConnectionAttemptResult Connect(string host, ushort remotePort, string passwordData, int passwordDataLength, PublicKey publicKey) { ConnectionAttemptResult ret = (ConnectionAttemptResult)RakNetPINVOKE.CSharp_RakNet_RakPeerInterface_Connect__SWIG_4(swigCPtr, host, remotePort, passwordData, passwordDataLength, PublicKey.getCPtr(publicKey)); return(ret); }
/** * Connect to the externally hosted NAT Facilitator (NATCompleteServer from the RakNet samples) * This is called initially and also after each succesfull punchthrough received on the server. */ IEnumerator connectToNATFacilitator() { // Start the RakNet interface listening on a random port // We never need more than 2 connections, one to the Facilitator and one to either the server or the latest incoming client // Each time a client connects on the server RakNet is shut down and restarted with two fresh connections StartupResult startResult = rakPeer.Startup(2, new SocketDescriptor(), 1); if (startResult != StartupResult.RAKNET_STARTED) { Debug.Log("Failed to initialize network interface: " + startResult.ToString()); yield break; } // Connect to the Facilitator ConnectionAttemptResult connectResult = rakPeer.Connect(facilitatorIP, (ushort)facilitatorPort, null, 0); if (connectResult != ConnectionAttemptResult.CONNECTION_ATTEMPT_STARTED) { Debug.Log("Failed to initialize connection to NAT Facilitator: " + connectResult.ToString()); yield break; } // Connecting, wait for response Packet packet; while ((packet = rakPeer.Receive()) == null) { yield return(new WaitForEndOfFrame()); } // Was the connection accepted? if (packet.data[0] != (byte)DefaultMessageIDTypes.ID_CONNECTION_REQUEST_ACCEPTED) { Debug.Log("Failed to connect to NAT Facilitator: " + ((DefaultMessageIDTypes)packet.data[0])); yield break; } // Success, we are connected to the Facilitator guid = rakPeer.GetMyGUID().g.ToString(); Debug.Log("Connected: " + guid); // We store this for later so that we can tell which incoming messages are coming from the facilitator facilitatorSystemAddress = packet.systemAddress; // Now that we have an external connection we can get the externalIP externalIP = rakPeer.GetExternalID(packet.systemAddress).ToString(false); if (firstTimeConnect) { firstTimeConnect = false; // Attach RakNet punchthrough client // This is really what does all the heavy lifting natPunchthroughClient = new NatPunchthroughClient(); rakPeer.AttachPlugin(natPunchthroughClient); // Punchthrough can't happen until RakNet is done finding router port stride // so we start it asap. If we didn't call this here RakNet would handle it // when we actually try and punch through. natPunchthroughClient.FindRouterPortStride(facilitatorSystemAddress); } else { // If this is not the first time connecting to the facilitor it means the server just received // a successful punchthrough and it reconnecting to prepare for more punching. We can start // listening immediately. StartCoroutine(waitForIncomingNATPunchThroughOnServer(onHolePunched)); } isReady = true; }
static void Main(string[] args) { RakNetStatistics rss = new RakNetStatistics(); RakPeerInterface client = RakPeerInterface.GetInstance(); Packet p = new Packet(); byte packetIdentifier; bool isServer = false; SystemAddress ClientID = RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS; string ip, serverPort, clientPort; Console.WriteLine("This is a sample implementation of a text based chat client"); Console.WriteLine("Connect to the project 'Chat Example Server'"); Console.WriteLine("Enter the client port to listen on"); clientPort = Console.ReadLine(); if (clientPort.Length == 0) { clientPort = "0"; } Console.WriteLine("Enter the IP to connect to"); ip = Console.ReadLine(); if (ip.Length == 0) { ip = "127.0.0.1"; } Console.WriteLine("Enter the port to connect to"); serverPort = Console.ReadLine(); if (serverPort.Length == 0) { serverPort = "1234"; } SocketDescriptor socketDescriptor = new SocketDescriptor(Convert.ToUInt16(clientPort), "0"); socketDescriptor.socketFamily = AF_INET; client.Startup(8, socketDescriptor, 1); client.SetOccasionalPing(true); ConnectionAttemptResult car = client.Connect(ip, Convert.ToUInt16(serverPort), "Rumpelstiltskin", "Rumpelstiltskin".Length); if (car != RakNet.ConnectionAttemptResult.CONNECTION_ATTEMPT_STARTED) { throw new Exception(); } Console.WriteLine("My IP Addresses:"); for (uint i = 0; i < client.GetNumberOfAddresses(); i++) { Console.WriteLine(client.GetLocalIP(i).ToString()); } Console.WriteLine("My GUID is " + client.GetGuidFromSystemAddress(RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS).ToString()); Console.WriteLine("'quit' to quit. 'stat' to show stats. 'ping' to ping.\n'disconnect' to disconnect. 'connect' to reconnnect. Type to talk."); string message; while (true) { System.Threading.Thread.Sleep(30); //Entire networking is threaded if (Console.KeyAvailable) { message = Console.ReadLine(); if (message == "quit") { Console.WriteLine("Quitting"); break; } if (message == "stat") { string message2 = ""; rss = client.GetStatistics(client.GetSystemAddressFromIndex(0)); RakNet.RakNet.StatisticsToString(rss, out message2, 2); Console.WriteLine(message2); continue; } if (message == "disconnect") { Console.WriteLine("Enter index to disconnect: "); string str = Console.ReadLine(); if (str == "") { str = "0"; } uint index = Convert.ToUInt32(str, 16); client.CloseConnection(client.GetSystemAddressFromIndex(index), false); Console.WriteLine("Disconnecting"); continue; } if (message == "shutdown") { client.Shutdown(100); Console.WriteLine("Disconnecting"); continue; } if (message == "ping") { if (client.GetSystemAddressFromIndex(0) != RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS) { client.Ping(client.GetSystemAddressFromIndex(0)); } continue; } if (message == "connect") { Console.WriteLine("Enter the IP to connect to"); ip = Console.ReadLine(); if (ip.Length == 0) { ip = "127.0.0.1"; } Console.WriteLine("Enter the port to connect to"); serverPort = Console.ReadLine(); if (serverPort.Length == 0) { serverPort = "1234"; } ConnectionAttemptResult car2 = client.Connect(ip, Convert.ToUInt16(serverPort), "Rumpelstiltskin", "Rumpelstiltskin".Length); continue; } if (message == "getlastping") { if (client.GetSystemAddressFromIndex(0) != RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS) { Console.WriteLine(client.GetLastPing(client.GetSystemAddressFromIndex(0))); } continue; } if (message.Length > 0) { client.Send(message, message.Length + 1, PacketPriority.HIGH_PRIORITY, PacketReliability.RELIABLE_ORDERED, (char)0, RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS, true); } } for (p = client.Receive(); p != null; client.DeallocatePacket(p), p = client.Receive()) { packetIdentifier = GetPacketIdentifier(p); switch ((DefaultMessageIDTypes)packetIdentifier) { case DefaultMessageIDTypes.ID_DISCONNECTION_NOTIFICATION: Console.WriteLine("ID_DISCONNECTION_NOTIFICATION"); break; case DefaultMessageIDTypes.ID_ALREADY_CONNECTED: Console.WriteLine("ID_ALREADY_CONNECTED with guid " + p.guid); break; case DefaultMessageIDTypes.ID_INCOMPATIBLE_PROTOCOL_VERSION: Console.WriteLine("ID_INCOMPATIBLE_PROTOCOL_VERSION "); break; case DefaultMessageIDTypes.ID_REMOTE_DISCONNECTION_NOTIFICATION: Console.WriteLine("ID_REMOTE_DISCONNECTION_NOTIFICATION "); break; case DefaultMessageIDTypes.ID_REMOTE_CONNECTION_LOST: // Server telling the clients of another client disconnecting forcefully. You can manually broadcast this in a peer to peer enviroment if you want. Console.WriteLine("ID_REMOTE_CONNECTION_LOST"); break; case DefaultMessageIDTypes.ID_CONNECTION_BANNED: // Banned from this server Console.WriteLine("We are banned from this server.\n"); break; case DefaultMessageIDTypes.ID_CONNECTION_ATTEMPT_FAILED: Console.WriteLine("Connection attempt failed "); break; case DefaultMessageIDTypes.ID_NO_FREE_INCOMING_CONNECTIONS: Console.WriteLine("Server is full "); break; case DefaultMessageIDTypes.ID_INVALID_PASSWORD: Console.WriteLine("ID_INVALID_PASSWORD\n"); break; case DefaultMessageIDTypes.ID_CONNECTION_LOST: // Couldn't deliver a reliable packet - i.e. the other system was abnormally // terminated Console.WriteLine("ID_CONNECTION_LOST\n"); break; case DefaultMessageIDTypes.ID_CONNECTION_REQUEST_ACCEPTED: // This tells the client they have connected Console.WriteLine("ID_CONNECTION_REQUEST_ACCEPTED to %s " + p.systemAddress.ToString() + "with GUID " + p.guid.ToString()); Console.WriteLine("My external address is:" + client.GetExternalID(p.systemAddress).ToString()); break; case DefaultMessageIDTypes.ID_CONNECTED_PING: case DefaultMessageIDTypes.ID_UNCONNECTED_PING: Console.WriteLine("Ping from " + p.systemAddress.ToString(true)); break; default: Console.WriteLine(System.Text.Encoding.UTF8.GetString(p.data)); break; } } } client.Shutdown(300); RakNet.RakPeerInterface.DestroyInstance(client); Console.Read(); }