public void StartServer(ushort port, string password, bool occasionalPing = true, ushort maxConnection = 4, uint unrealiableTimeout = 1000) { server = RakPeerInterface.GetInstance(); server.SetIncomingPassword(password, password.Length);// "Rumpelstiltskin" server.SetTimeoutTime(30000, RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS); p = new Packet(); SystemAddress clientID = RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS; SocketDescriptor socketDesc = new SocketDescriptor(port, ""); StartupResult result = server.Startup(maxConnection, socketDesc, 1); server.SetMaximumIncomingConnections(maxConnection); if (result != StartupResult.RAKNET_STARTED) { MessageBox("Server failed to start. Terminating."); } else { MessageBox("Server start successfully"); } server.SetOccasionalPing(occasionalPing); server.SetUnreliableTimeout(unrealiableTimeout); StringBuilder ipsb = new StringBuilder(); for (int i = 0; i < server.GetNumberOfAddresses(); i++) { SystemAddress sa = server.GetInternalID(RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS, i); ipsb.Append(string.Format("{0}. {1}", i + 1, sa.ToString(false))); } ServerIP = ipsb.ToString(); GUID = server.GetGuidFromSystemAddress(RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS).ToString(); lis = new Thread(Listening); lis.Start(); }
public void Start(ushort port, ushort maxConnections, String pw) { pw = "ver2.081" + pw; SocketDescriptor socketDescriptor = new SocketDescriptor(); socketDescriptor.port = port; bool started = ServerInterface.Startup(maxConnections, socketDescriptor, 1) == StartupResult.RAKNET_STARTED; ServerInterface.SetMaximumIncomingConnections(maxConnections); ServerInterface.SetOccasionalPing(true); if (pw.Length != 0) { ServerInterface.SetIncomingPassword(pw, pw.Length); } if (!started) { Log.Logger.logError("Port is already in use"); } else { Log.Logger.log("Server start listening on port " + port); } }
internal bool Start(RaknetIPAddress localAddress = null, ushort maxConnCount = ushort.MaxValue) { rakPeer.AttachPlugin(udpProxyCoordinator); udpProxyCoordinator.SetRemoteLoginPassword(RaknetConfig.COORDINATOR_PASSWORD); rakPeer.SetMaximumIncomingConnections(maxConnCount); SocketDescriptor socketDescriptor = new SocketDescriptor(); if (localAddress != null && !string.IsNullOrWhiteSpace(localAddress.Address) && localAddress.Port > 0) { socketDescriptor.hostAddress = localAddress.Address; socketDescriptor.port = localAddress.Port; } var startResult = rakPeer.Startup(maxConnCount, socketDescriptor, 1); if (startResult == StartupResult.SOCKET_PORT_ALREADY_IN_USE) { RaknetExtension.WriteWarning(string.Format(@"{0}端口被占用", socketDescriptor.port)); return(false); } OnUdpProxyGeneral += RaknetUdpProxyCoordinator_OnUdpProxyGeneral; ReceiveThreadStart(); List <int> startList = new List <int>() { (int)StartupResult.RAKNET_STARTED, (int)StartupResult.RAKNET_ALREADY_STARTED, }; if (startList.Any(m => m == (int)startResult)) { return(true); } isThreadRunning = false; return(false); }
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()); }
static GameClient() { Client = ScriptManager.Interface.CreateClient(); // Init RakNet objects clientInterface = RakPeerInterface.GetInstance(); clientInterface.SetOccasionalPing(true); socketDescriptor = new SocketDescriptor(); socketDescriptor.port = 0; if (clientInterface.Startup(1, socketDescriptor, 1) != StartupResult.RAKNET_STARTED) { Logger.LogError("RakNet failed to start!"); } // Init debug info on screen var screenSize = GUCView.GetScreenSize(); abortInfo = new GUCVisual((screenSize.Y - 300) / 2, 150, 300, 40); abortInfo.SetBackTexture("Menu_Choice_Back.tga"); GUCVisualText visText = abortInfo.CreateText("Verbindung unterbrochen!"); visText.SetColor(ColorRGBA.Red); devInfo = new GUCVisual(); for (int pos = 0; pos < 0x2000; pos += devInfo.zView.FontY() + 5) { var t = devInfo.CreateText("", 0x2000, pos, true); t.Format = GUCVisualText.TextFormat.Right; } devInfo.Show(); }
static GameServer() { using (SocketDescriptor socketDescriptor = new SocketDescriptor()) { socketDescriptor.port = ServerOptions.Port; StartupResult res = ServerInterface.Startup(ServerOptions.Slots, socketDescriptor, 1); if (res == StartupResult.RAKNET_STARTED) { Logger.Log("Server starts RakNet on port " + ServerOptions.Port); } else { throw new Exception("RakNet startup failed: " + res.ToString()); } ServerInterface.SetMaximumIncomingConnections(ServerOptions.Slots); ServerInterface.SetOccasionalPing(true); if (ServerOptions.Password != null) { string pwStr = Convert.ToBase64String(ServerOptions.Password.ToArray()); ServerInterface.SetIncomingPassword(pwStr, pwStr.Length); } } }
public bool Start(RaknetIPAddress localAddress = null, ushort maxConnCount = ushort.MaxValue) { rakPeer.AttachPlugin(natPunchthroughServer); rakPeer.SetMaximumIncomingConnections(maxConnCount); SocketDescriptor socketDescriptor = new SocketDescriptor(); if (localAddress != null && !string.IsNullOrWhiteSpace(localAddress.Address) && localAddress.Port > 0) { socketDescriptor.hostAddress = localAddress.Address; socketDescriptor.port = localAddress.Port; } var startResult = rakPeer.Startup(maxConnCount, socketDescriptor, 1); if (startResult == StartupResult.SOCKET_PORT_ALREADY_IN_USE) { RaknetExtension.WriteWarning(string.Format(@"{0}端口被占用", socketDescriptor.port)); return(false); } ReceiveThreadStart(); List <int> startList = new List <int>() { (int)StartupResult.RAKNET_STARTED, (int)StartupResult.RAKNET_ALREADY_STARTED, }; if (startList.Any(m => m == (int)startResult)) { return(true); } isThreadRunning = false; return(false); }
public void Startup() { socketDescriptor = new SocketDescriptor(); socketDescriptor.port = 0; bool started = client.Startup(1, socketDescriptor, 1) == StartupResult.RAKNET_STARTED; isConnected = false; }
public StartupResult Startup(ushort port, ushort maxConnect) { _Socket = new SocketDescriptor(port, ""); StartupResult result = _peer.Startup(maxConnect, _Socket, 1); _peer.SetMaximumIncomingConnections(maxConnect); Log.Info("RakPeerInterface.Startup(" + port + ")" + result); if (result == StartupResult.RAKNET_STARTED) { ProcessMessage(); } return(result); }
public (SocketDescriptor, ChannelReader <byte>) GetNewSocket(PipeWriter writer) { Interlocked.Add(ref CurrentNum, 1); // We only ever need a channel of depth 1 here: if we returned a non-full write to the PeerManager, // we will eventually get notified that there is room in the socket to write new bytes, which will generate // an event. That event will be popped off the queue before we call WriteBufferSpaceAvail, ensuring that we // have room to push a new () if, during the WriteBufferSpaceAvail call, send_data() returns a non-full write. var writeAvail = Channel.CreateBounded <byte>(1); Sockets[CurrentNum] = new SocketDescriptor((UIntPtr)CurrentNum, writer, loggerFactory.CreateLogger <SocketDescriptor>(), writeAvail.Writer); return(Sockets[(int)CurrentNum], writeAvail.Reader); }
static void Main(string[] args) { const ushort PORT = 5456; RakNet.RakPeerInterface peerInterface; // console out starting up the server //Initialize the raknet peer interface first peerInterface = RakNet.RakPeerInterface.GetInstance(); //Create a socket descriptor to describe this connection. RakNet.SocketDescriptor socketDescriptor; socketDescriptor = new SocketDescriptor(PORT, "0"); //Now call startup - max of 32 connections, on the assigned port peerInterface.Startup(32, socketDescriptor, 1); peerInterface.SetMaximumIncomingConnections(32); }
public RaknetUdpPeerClient Start(RaknetIPAddress localAddress = null, ushort maxConnCount = ushort.MaxValue) { rakPeer.AttachPlugin(natPunchthroughClient); rakPeer.AttachPlugin(udpProxyClient); SocketDescriptor socketDescriptor = new SocketDescriptor(); if (localAddress != null && !string.IsNullOrWhiteSpace(localAddress.Address) && localAddress.Port > 0) { socketDescriptor.hostAddress = localAddress.Address; socketDescriptor.port = localAddress.Port; } var startResult = rakPeer.Startup(maxConnCount, socketDescriptor, 1); if (startResult == StartupResult.SOCKET_PORT_ALREADY_IN_USE) { RaknetExtension.WriteWarning(string.Format(@"{0}端口被占用", socketDescriptor.port)); } return(this); }
private void Start() { const ushort PORT = 5456; RakNet.RakPeerInterface rakPeerInterface; // console out starting up the server //Initialize the raknet peer interface first rakPeerInterface = RakNet.RakPeerInterface.GetInstance(); //Create a socket descriptor to describe this connection. RakNet.SocketDescriptor socketDescriptor; socketDescriptor = new SocketDescriptor(PORT, "0"); //Now call startup - max of 32 connections, on the assigned port rakPeerInterface.Startup(32, socketDescriptor, 1); rakPeerInterface.SetMaximumIncomingConnections(32); handleNetworkMessages(rakPeerInterface); }
internal RaknetUdpProxyServer Start(RaknetIPAddress localAddress = null, ushort maxConnCount = ushort.MaxValue) { rakPeer.AttachPlugin(udpProxyServer); udpProxyServer.SetResultHandler(new MyUDPProxyServerResultHandler()); rakPeer.SetMaximumIncomingConnections(maxConnCount); SocketDescriptor socketDescriptor = new SocketDescriptor(); if (localAddress != null && !string.IsNullOrWhiteSpace(localAddress.Address) && localAddress.Port > 0) { socketDescriptor.hostAddress = localAddress.Address; socketDescriptor.port = localAddress.Port; } var startResult = rakPeer.Startup(maxConnCount, socketDescriptor, 1); if (startResult == StartupResult.SOCKET_PORT_ALREADY_IN_USE) { RaknetExtension.WriteWarning(string.Format(@"proxyServer {0}端口被占用", socketDescriptor.port)); return(this); } return(this); }
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 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); } }
/// <summary> /// 启动是否成功 /// </summary> /// <returns></returns> public bool StartUpRaknet(bool isIPV6) { if (IsStartUp == false) { if (mClient == null) { mClient = RakPeerInterface.GetInstance(); } SocketDescriptor descriptor = new SocketDescriptor(); //descriptor.port = 0; if (isIPV6 == true) { // 这里有尼玛个天坑,AF_INET6 這个宏在windows下的值是23,在 mac osx下的值是30 descriptor.socketFamily = 30; } else { descriptor.socketFamily = 2; } StartupResult result = mClient.Startup(1, descriptor, 1); if (result == StartupResult.RAKNET_STARTED) { IsStartUp = true; return(true); } else { Debug.LogError(string.Format("初始化raknet失败,result = {0}", result)); return(false); } } else { return(true); } }
protected virtual void Dispose(bool disposing) { // If you need thread safety, use a lock around these // operations, as well as in your methods that use the resource. if (!_disposed) { if (disposing) { if (client != null) { client.CloseConnection(client.GetSystemAddressFromIndex(0), true, 0); client.Dispose(); } if (socketDescriptor != null) { socketDescriptor.Dispose(); } if (receiveBitStream != null) { receiveBitStream.Dispose(); } if (sentBitStream != null) { sentBitStream.Dispose(); } } client = null; socketDescriptor = null; receiveBitStream = null; sentBitStream = null; _disposed = true; } }
static void Main(string[] args) { RakNetStatistics rss = new RakNetStatistics(); RakPeerInterface server = RakPeerInterface.GetInstance(); server.SetIncomingPassword("Rumpelstiltskin", "Rumpelstiltskin".Length); server.SetTimeoutTime(30000, RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS); Packet p = new Packet(); RakNet.SystemAddress clientID = RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS; byte packetIdentifier; bool isServer = true; string serverPort; Console.WriteLine("Enter the client port to listen on"); serverPort = Console.ReadLine(); if (serverPort.Length == 0) { serverPort = "1234"; } Console.WriteLine("Starting server"); RakNet.SocketDescriptor socketDescriptors = new SocketDescriptor(Convert.ToUInt16(serverPort), "0"); socketDescriptors.port = Convert.ToUInt16(serverPort); socketDescriptors.socketFamily = AF_INET; StartupResult sar = server.Startup(4, socketDescriptors, 1); if (sar != StartupResult.RAKNET_STARTED) { Console.WriteLine("Error starting server"); } server.SetMaximumIncomingConnections(4); System.Threading.Thread.Sleep(1000); server.SetOccasionalPing(true); server.SetUnreliableTimeout(1000); for (int i = 0; i < server.GetNumberOfAddresses(); i++) { SystemAddress sa = server.GetInternalID(RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS, i); Console.WriteLine((i + 1).ToString() + ". " + sa.ToString() + "(LAN = " + sa.IsLANAddress() + ")"); } Console.WriteLine("My GUID is " + server.GetGuidFromSystemAddress(RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS).ToString()); Console.WriteLine("'quit' to quit. 'stat' to show stats. 'ping' to ping.\n'pingip' to ping an ip address\n'ban' to ban an IP from connecting.\n'kick to kick the first connected player.\nType to talk."); string message; while (true) { System.Threading.Thread.Sleep(30); if (Console.KeyAvailable) { message = Console.ReadLine(); if (message == "quit") { Console.WriteLine("Quitting"); break; } if (message == "kick") { server.CloseConnection(clientID, true, 0); continue; } if (message == "stat") { rss = server.GetStatistics(server.GetSystemAddressFromIndex(0)); RakNet.RakNet.StatisticsToString(rss, out message, 2); Console.WriteLine(message); continue; } if (message == "ping") { server.Ping(clientID); continue; } if (message == "list") { SystemAddress[] systems = new SystemAddress[10]; ushort numCons = 10; server.GetConnectionList(out systems, ref numCons); for (int i = 0; i < numCons; i++) { Console.WriteLine((i + 1).ToString() + ". " + systems[i].ToString(true)); } continue; } if (message == "ban") { Console.WriteLine("'Enter IP to ban. You can use * as a wildcard"); message = Console.ReadLine(); server.AddToBanList(message); Console.WriteLine("IP " + message + " added to ban list."); continue; } string message2; message2 = "Server: " + message; server.Send(message2, message2.Length + 1, PacketPriority.HIGH_PRIORITY, PacketReliability.RELIABLE_ORDERED, (char)0, RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS, true); } for (p = server.Receive(); p != null; server.DeallocatePacket(p), p = server.Receive()) { packetIdentifier = GetPacketIdentifier(p); switch ((DefaultMessageIDTypes)packetIdentifier) { case DefaultMessageIDTypes.ID_DISCONNECTION_NOTIFICATION: Console.WriteLine("ID_DISCONNECTION_NOTIFICATION from " + p.systemAddress.ToString(true)); break; case DefaultMessageIDTypes.ID_NEW_INCOMING_CONNECTION: Console.WriteLine("ID_NEW_INCOMING_CONNECTION from " + p.systemAddress.ToString(true) + "with GUID " + p.guid.ToString()); clientID = p.systemAddress; Console.WriteLine("Remote internal IDs: "); for (int index = 0; index < MAXIMUM_NUMBER_OF_INTERNAL_IDS; index++) { SystemAddress internalId = server.GetInternalID(p.systemAddress, index); if (internalId != RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS) { Console.WriteLine((index + 1).ToString() + ". " + internalId.ToString(true)); } } break; case DefaultMessageIDTypes.ID_INCOMPATIBLE_PROTOCOL_VERSION: Console.WriteLine("ID_INCOMPATIBLE_PROTOCOL_VERSION"); break; case DefaultMessageIDTypes.ID_CONNECTED_PING: case DefaultMessageIDTypes.ID_UNCONNECTED_PING: Console.WriteLine("Ping from " + p.systemAddress.ToString(true)); break; case DefaultMessageIDTypes.ID_CONNECTION_LOST: Console.WriteLine("ID_CONNECTION_LOST from " + p.systemAddress.ToString(true)); break; default: Console.WriteLine(System.Text.Encoding.UTF8.GetString(p.data)); message = System.Text.Encoding.UTF8.GetString(p.data); server.Send(message, message.Length + 1, PacketPriority.HIGH_PRIORITY, PacketReliability.RELIABLE_ORDERED, (char)0, RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS, true); break; } } } server.Shutdown(300); RakNet.RakPeerInterface.DestroyInstance(server); Console.Read(); }
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(); }
public virtual StartupResult Startup(uint maxConnections, SocketDescriptor socketDescriptors, uint socketDescriptorCount) { StartupResult ret = (StartupResult)RakNetPINVOKE.CSharp_RakNet_RakPeerInterface_Startup__SWIG_1(swigCPtr, maxConnections, SocketDescriptor.getCPtr(socketDescriptors), socketDescriptorCount); return(ret); }
public override StartupResult Startup(uint maxConnections, SocketDescriptor socketDescriptors, uint socketDescriptorCount, int threadPriority) { StartupResult ret = (StartupResult)RakNetPINVOKE.CSharp_RakNet_RakPeer_Startup__SWIG_0(swigCPtr, maxConnections, SocketDescriptor.getCPtr(socketDescriptors), socketDescriptorCount, threadPriority); return(ret); }
private void Run(CancellationToken token, ushort?serverPort, ushort maxConnections, TaskCompletionSource <bool> startupTcs) { IsRunning = true; logger.Info("Starting raknet transport " + _type); RakPeerInterface server; try { server = RakPeerInterface.GetInstance(); } catch (Exception ex) { logger.Error(ex); throw; } var socketDescriptorList = new RakNetListSocketDescriptor(); //var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces(); if (Socket.SupportsIPv4) { logger.Info("A valid ipv4 address was found."); var socketDescriptorIpv4 = new SocketDescriptor(serverPort.GetValueOrDefault(), null); socketDescriptorList.Push(socketDescriptorIpv4, null, 0); } else { logger.Info("No valid ipv4 address was found."); } #if (!UNITY_ANDROID) if (Socket.OSSupportsIPv6) { logger.Info("A valid ipv6 address was found."); var socketDescriptorIpv6 = new SocketDescriptor(serverPort.GetValueOrDefault(), null); socketDescriptorIpv6.socketFamily = 23; // AF_INET6 socketDescriptorList.Push(socketDescriptorIpv6, null, 0); } else { logger.Info("No valid ipv6 address was found."); } #endif var startupResult = server.Startup(maxConnections, socketDescriptorList, 1); if (startupResult != StartupResult.RAKNET_STARTED) { logger.Error("Couldn't start raknet peer :" + startupResult); throw new InvalidOperationException("Couldn't start raknet peer :" + startupResult); } server.SetMaximumIncomingConnections(maxConnections); _peer = server; startupTcs.SetResult(true); logger.Info("Raknet transport " + _type + " started"); while (!token.IsCancellationRequested) { for (var packet = server.Receive(); packet != null; packet = server.Receive()) { switch (packet.data[0]) { case (byte)DefaultMessageIDTypes.ID_CONNECTION_REQUEST_ACCEPTED: IConnection c; try { c = OnConnection(packet, server); } catch (Exception e) { UnityEngine.Debug.LogException(e); throw; } logger.Debug("Connection request to {0} accepted.", packet.systemAddress.ToString()); var pendingConnection = _pendingConnections.Dequeue(); if (pendingConnection != null) { pendingConnection.Tcs.SetResult(c); logger.Trace("Task for the connection request to {0} completed.", packet.systemAddress.ToString()); } else { logger.Log(Diagnostics.LogLevel.Warn, "RaknetTransport", "Unknown pending connection accepted: '" + packet.systemAddress.ToString() + "'"); } break; case (byte)DefaultMessageIDTypes.ID_NEW_INCOMING_CONNECTION: logger.Trace("Incoming connection from {0}.", packet.systemAddress.ToString()); OnConnection(packet, server); break; case (byte)DefaultMessageIDTypes.ID_DISCONNECTION_NOTIFICATION: logger.Trace("{0} disconnected.", packet.systemAddress.ToString()); OnDisconnection(packet, server, "CLIENT_DISCONNECTED"); break; case (byte)DefaultMessageIDTypes.ID_CONNECTION_LOST: logger.Trace("{0} lost the connection.", packet.systemAddress.ToString()); OnDisconnection(packet, server, "CONNECTION_LOST"); break; case (byte)MessageIDTypes.ID_CONNECTION_RESULT: OnConnectionIdReceived(BitConverter.ToInt64(packet.data, 1)); break; case (byte)DefaultMessageIDTypes.ID_CONNECTION_ATTEMPT_FAILED: pendingConnection = _pendingConnections.Dequeue(); if (pendingConnection != null) { pendingConnection.Tcs.SetException(new InvalidOperationException("Connection attempt for endpoint " + pendingConnection.Endpoint + " failed.")); } else { logger.Log(Diagnostics.LogLevel.Warn, "RaknetTransport", "Unknown pending connection failed: '" + packet.systemAddress.ToString() + "'"); } break; default: OnMessageReceived(packet); break; } } Thread.Sleep(5); } server.Shutdown(1000); RakPeerInterface.DestroyInstance(server); IsRunning = false; logger.Info("Stopped raknet server."); }
public virtual StartupResult Startup(uint maxConnections, SocketDescriptor socketDescriptors, uint socketDescriptorCount, int threadPriority) { StartupResult ret = (StartupResult)RakNetPINVOKE.RakPeerInterface_Startup__SWIG_0(swigCPtr, maxConnections, SocketDescriptor.getCPtr(socketDescriptors), socketDescriptorCount, threadPriority); return(ret); }
static void Main(string[] args) { int BIG_PACKET_SIZE = 103296250; bool quit; bool sentPacket = false; RakPeerInterface client, server; byte[] text; string message; client = server = null; string ip = string.Empty; text = new byte[BIG_PACKET_SIZE]; quit = false; char ch; Console.WriteLine("Enter 's' to run as server, 'c' to run as client, space to run local."); ch = ' '; message = Console.ReadLine(); ch = message.ToCharArray()[0]; if (ch == 'c') { client = RakPeerInterface.GetInstance(); Console.WriteLine("Working as client"); Console.WriteLine("Enter remote IP: "); ip = Console.ReadLine(); if (ip.Length == 0) { ip = "127.0.0.1"; } } else if (ch == 's') { server = RakPeerInterface.GetInstance(); Console.WriteLine("Working as server"); } else { client = RakPeerInterface.GetInstance(); server = RakPeerInterface.GetInstance(); ip = "127.0.0.1"; } short socketFamily; socketFamily = AF_INET; if (server != null) { server.SetTimeoutTime(5000, RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS); SocketDescriptor socketDescriptor = new SocketDescriptor(3000, "0"); socketDescriptor.socketFamily = socketFamily; server.SetMaximumIncomingConnections(4); StartupResult sr = new StartupResult(); sr = server.Startup(4, socketDescriptor, 1); if (sr != StartupResult.RAKNET_STARTED) { Console.WriteLine("Error: Server failed to start: {0} ", sr.ToString()); return; } // server.SetPerConnectionOutgoingBandwidthLimit(50000); Console.WriteLine("Server started on {0}", server.GetMyBoundAddress().ToString()); } if (client != null) { client.SetTimeoutTime(5000, RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS); SocketDescriptor socketDescriptor = new SocketDescriptor(0, "0"); socketDescriptor.socketFamily = socketFamily; client.SetMaximumIncomingConnections(4); StartupResult sr = new StartupResult(); sr = client.Startup(4, socketDescriptor, 1); if (sr != StartupResult.RAKNET_STARTED) { Console.WriteLine("Error: Server failed to start: " + sr.ToString()); return; } client.SetSplitMessageProgressInterval(10000); // Get ID_DOWNLOAD_PROGRESS notifications client.SetPerConnectionOutgoingBandwidthLimit(10000); Console.WriteLine("Client started on {0}", client.GetMyBoundAddress().ToString()); client.Connect(ip, 3000, null, 0); } System.Threading.Thread.Sleep(500); Console.WriteLine("My IP addresses: "); RakPeerInterface rakPeer; if (server != null) { rakPeer = server; } else { rakPeer = client; } for (uint i = 0; i < rakPeer.GetNumberOfAddresses(); i++) { Console.WriteLine("{0}. {1}", (i + 1).ToString(), rakPeer.GetLocalIP(i).ToString()); } uint start, stop = 0; uint nextStatTime = RakNet.RakNet.GetTimeMS() + 1000; Packet packet = new Packet(); start = RakNet.RakNet.GetTimeMS(); while (!quit) { if (server != null) { for (packet = server.Receive(); packet != null; server.DeallocatePacket(packet), packet = server.Receive()) { if ((DefaultMessageIDTypes)packet.data[0] == DefaultMessageIDTypes.ID_NEW_INCOMING_CONNECTION || packet.data[0] == (int)253) { Console.WriteLine("Starting send"); start = RakNet.RakNet.GetTimeMS(); if (BIG_PACKET_SIZE < 100000) { for (int i = 0; i < BIG_PACKET_SIZE; i++) { text[i] = (byte)(255 - (i & 255)); } } else { text[0] = (byte)255; } DefaultMessageIDTypes idtype = (DefaultMessageIDTypes)packet.data[0]; if (idtype == DefaultMessageIDTypes.ID_CONNECTION_LOST) { Console.WriteLine("ID_CONNECTION_LOST from {0}", packet.systemAddress.ToString()); } else if (idtype == DefaultMessageIDTypes.ID_DISCONNECTION_NOTIFICATION) { Console.WriteLine("ID_DISCONNECTION_NOTIFICATION from {0}", packet.systemAddress.ToString()); } else if (idtype == DefaultMessageIDTypes.ID_NEW_INCOMING_CONNECTION) { Console.WriteLine("ID_NEW_INCOMING_CONNECTION from {0}", packet.systemAddress.ToString()); } else if (idtype == DefaultMessageIDTypes.ID_CONNECTION_REQUEST_ACCEPTED) { Console.WriteLine("ID_CONNECTION_REQUEST_ACCEPTED from {0}", packet.systemAddress.ToString()); } server.Send(text, BIG_PACKET_SIZE, PacketPriority.LOW_PRIORITY, PacketReliability.RELIABLE_ORDERED_WITH_ACK_RECEIPT, (char)0, packet.systemAddress, false); } } if (Console.KeyAvailable) { ConsoleKeyInfo key = Console.ReadKey(); switch (key.Key) { case ConsoleKey.Spacebar: Console.WriteLine("Sending medium priority message"); byte[] t = new byte[1]; t[0] = 254; server.Send(t, 1, PacketPriority.MEDIUM_PRIORITY, PacketReliability.RELIABLE_ORDERED, (char)1, RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS, true); break; case ConsoleKey.Q: quit = true; break; default: break; } } } if (client != null) { packet = client.Receive(); while (packet != null) { DefaultMessageIDTypes idtype = (DefaultMessageIDTypes)packet.data[0]; if (idtype == DefaultMessageIDTypes.ID_DOWNLOAD_PROGRESS) { BitStream progressBS = new BitStream(packet.data, packet.length, false); progressBS.IgnoreBits(8); byte[] progress = new byte[4], total = new byte[4], partlength = new byte[4]; progressBS.ReadBits(progress, sizeof(uint) << 3, true); progressBS.ReadBits(total, sizeof(uint) << 3, true); progressBS.ReadBits(partlength, sizeof(uint) << 3, true); Console.WriteLine("Progress: msgID= {0}, Progress: {1} / {2}, Partsize: {3}", packet.data[0].ToString(), BitConverter.ToUInt32(progress, 0).ToString(), BitConverter.ToUInt32(total, 0).ToString(), BitConverter.ToUInt32(partlength, 0).ToString()); } else if (packet.data[0] == 255) { if (packet.length != BIG_PACKET_SIZE) { Console.WriteLine("Test failed. {0} bytes (wrong number of bytes.", packet.length); quit = true; break; } if (BIG_PACKET_SIZE <= 100000) { for (int i = 0; i < BIG_PACKET_SIZE; i++) { if (packet.data[i] != 255 - (i & 255)) { Console.WriteLine("Test failed. {0} bytes (bad data).", packet.length); quit = true; break; } } } if (quit == false) { Console.WriteLine("Test Succeeded. {0} bytes.", packet.length); bool repeat = false; if (repeat) { Console.WriteLine("Rerequesting send."); byte[] ch2 = new byte[1]; ch2[0] = (byte)253; client.Send(ch2, 1, PacketPriority.MEDIUM_PRIORITY, PacketReliability.RELIABLE_ORDERED, (char)1, RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS, true); GC.Collect(); } else { quit = true; break; } } } else if ((int)packet.data[0] == 254) { Console.WriteLine("Got high priority message."); } else if ((DefaultMessageIDTypes)packet.data[0] == DefaultMessageIDTypes.ID_CONNECTION_LOST) { Console.WriteLine("ID_CONNECTION_LOST from {0}", packet.systemAddress.ToString()); } else if ((DefaultMessageIDTypes)packet.data[0] == DefaultMessageIDTypes.ID_NEW_INCOMING_CONNECTION) { Console.WriteLine("ID_NEW_INCOMING_CONNECTION from {0}", packet.systemAddress.ToString()); } else if ((DefaultMessageIDTypes)packet.data[0] == DefaultMessageIDTypes.ID_CONNECTION_REQUEST_ACCEPTED) { start = RakNet.RakNet.GetTimeMS(); Console.WriteLine("ID_CONNECTION_REQUEST_ACCEPTED from {0}", packet.systemAddress.ToString()); } else if ((DefaultMessageIDTypes)packet.data[0] == DefaultMessageIDTypes.ID_CONNECTION_ATTEMPT_FAILED) { Console.WriteLine("ID_CONNECTION_ATTEMPT_FAILED from {0}", packet.systemAddress.ToString()); } client.DeallocatePacket(packet); packet = client.Receive(); } } uint currenttime = RakNet.RakNet.GetTimeMS(); if (currenttime > nextStatTime) { nextStatTime = RakNet.RakNet.GetTimeMS() + 1000; RakNetStatistics rssSender = new RakNetStatistics(); RakNetStatistics rssReceiver = new RakNetStatistics(); string StatText; if (server != null) { ushort i; ushort numSystems = 1; server.GetConnectionList(null, ref numSystems); if (numSystems > 0) { for (i = 0; i < numSystems; i++) { server.GetStatistics(server.GetSystemAddressFromIndex(i), rssSender); RakNet.RakNet.StatisticsToString(rssSender, out StatText, 2); Console.WriteLine("==== System {0} ====", (i + 1).ToString()); Console.WriteLine("{0}", StatText); } } } if (client != null && server == null && client.GetGUIDFromIndex(0) != RakNet.RakNet.UNASSIGNED_RAKNET_GUID) { client.GetStatistics(client.GetSystemAddressFromIndex(0), rssReceiver); RakNet.RakNet.StatisticsToString(rssReceiver, out StatText, 2); Console.WriteLine("{0}", StatText); } } System.Threading.Thread.Sleep(100); } string StatTextEnd = ""; stop = RakNet.RakNet.GetTimeMS(); double seconds = (double)(stop - start) / 1000.0; if (server != null) { RakNetStatistics rssSender2 = server.GetStatistics(server.GetSystemAddressFromIndex(0)); RakNet.RakNet.StatisticsToString(rssSender2, out StatTextEnd, 2); Console.WriteLine("{0}", StatTextEnd); } Console.WriteLine("{0} bytes per second ({1} seconds). Press enter to quit", (int)((double)(BIG_PACKET_SIZE) / seconds), seconds); RakPeerInterface.DestroyInstance(server); RakPeerInterface.DestroyInstance(client); Console.Read(); }
public override StartupResult Startup(uint maxConnections, SocketDescriptor socketDescriptors, uint socketDescriptorCount) { StartupResult ret = (StartupResult)RakNetPINVOKE.RakPeer_Startup__SWIG_1(swigCPtr, maxConnections, SocketDescriptor.getCPtr(socketDescriptors), socketDescriptorCount); return(ret); }
internal static global::System.Runtime.InteropServices.HandleRef getCPtr(SocketDescriptor obj) { return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr); }