public RakPeerInterface GetRakPeerInterface() { global::System.IntPtr cPtr = RakNetPINVOKE.PluginInterface2_GetRakPeerInterface(swigCPtr); RakPeerInterface ret = (cPtr == global::System.IntPtr.Zero) ? null : new RakPeerInterface(cPtr, false); return(ret); }
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(); }
public static RakPeerInterface GetInstance() { global::System.IntPtr cPtr = RakNetPINVOKE.CSharp_RakNet_RakPeerInterface_GetInstance(); RakPeerInterface ret = (cPtr == global::System.IntPtr.Zero) ? null : new RakPeerInterface(cPtr, false); return(ret); }
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 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()); }
public static RakPeerInterface GetRakPeerInterface() { IntPtr cPtr = RakNetPINVOKE.RakNetworkFactory_GetRakPeerInterface(); RakPeerInterface ret = (cPtr == IntPtr.Zero) ? null : new RakPeerInterface(cPtr, false); return(ret); }
void Start() { rakPeer = RakPeerInterface.GetInstance(); rakPeer2 = RakPeerInterface.GetInstance(); StartCoroutine("WaitForNetwork"); }
private void OnDisconnection(RakNet.Packet packet, RakPeerInterface server, string reason) { logger.Trace("Disconnected from endpoint {0}", packet.systemAddress); var c = RemoveConnection(packet.guid); server.DeallocatePacket(packet); _handler.CloseConnection(c, reason); var action = ConnectionClosed; if (action != null) { action(c); } if (c != null) { var a = c.ConnectionClosed; if (a != null) { a(reason); } } }
private IConnection OnConnection(RakNet.Packet packet, RakPeerInterface server) { logger.Trace("Connected to endpoint {0}", packet.systemAddress); IConnection c = CreateNewConnection(packet.guid, server); var ctx = new PeerConnectedContext { Connection = c }; var pconnected = _connectionHandler.PeerConnected; if (pconnected != null) { pconnected(ctx); } c = ctx.Connection; server.DeallocatePacket(packet); _handler.NewConnection(c); var action = ConnectionOpened; if (action != null) { action(c); } c.SendSystem((byte)MessageIDTypes.ID_CONNECTION_RESULT, s => s.Write(BitConverter.GetBytes(c.Id), 0, 8)); return(c); }
public void Remove(RakPeerInterface recipient, IProtocolProcessor processor) { IDictionary<string, IProtocolProcessor> processors; if (processorsByRecipient.TryGetValue(recipient, out processors)) { processors.Remove(processor.ProtocolName); } }
private RakNetConnection CreateNewConnection(RakNetGUID raknetGuid, RakPeerInterface peer) { var cid = _handler.GenerateNewConnectionId(); var c = new RakNetConnection(raknetGuid, cid, peer, OnRequestClose); _connections.TryAdd(raknetGuid.g, c); return(c); }
public void Send(FileList fileList, RakPeerInterface rakPeer, SystemAddress recipient, ushort setID, PacketPriority priority, char orderingChannel, IncrementalReadInterface _incrementalReadInterface) { RakNetPINVOKE.FileListTransfer_Send__SWIG_1(swigCPtr, FileList.getCPtr(fileList), RakPeerInterface.getCPtr(rakPeer), SystemAddress.getCPtr(recipient), setID, (int)priority, orderingChannel, IncrementalReadInterface.getCPtr(_incrementalReadInterface)); if (RakNetPINVOKE.SWIGPendingException.Pending) { throw RakNetPINVOKE.SWIGPendingException.Retrieve(); } }
public void DisConnect() { m_Socket.CloseConnection(m_SystemAddress, false); m_Socket.Shutdown(300); RakPeerInterface.DestroyInstance(m_Socket); m_SystemAddress = null; m_Socket = null; OnDisconnected(); }
public void Close() { if (server != null) { server.Shutdown(300); RakPeer.DestroyInstance(server); } server = null; }
public void Close() { if (this.client != null) { this.client.Shutdown(300); RakPeer.DestroyInstance(this.client); } this.client = null; }
/// <summary> /// 停止 /// </summary> /// <param name="beforeAction"></param> internal void Stop(Action beforeAction = null) { beforeAction?.Invoke(); string myAddress = GetMyAddress().ToString(); isThreadRunning = false; rakPeer.Shutdown(10); RakPeerInterface.DestroyInstance(rakPeer); RaknetExtension.WriteWarning(string.Format("coordinator停止了:{0}", myAddress)); }
/// <summary> /// 停止 /// </summary> /// <param name="beforeAction"></param> public void Stop(Action beforeAction = null) { beforeAction?.Invoke(); string myAddress = GetMyAddress().ToString(); isThreadRunning = false; rakPeer.Shutdown(10); RakPeerInterface.DestroyInstance(rakPeer); Console.WriteLine("UdpNATPTServer停止了:{0}", myAddress); }
public void ConnectFacTest() { if (!connectedToFacTest) { rakPeerTest = RakPeerInterface.GetInstance(); //natPunchthroughClientTest = null; //facilitatorSystemAddressTest = null; StopCoroutine("connectToNATFacilitatorTest"); StartCoroutine("connectToNATFacilitatorTest"); } }
// <summary> /// 停止 /// </summary> /// <param name="beforeAction"></param> internal void Stop(Action beforeAction = null) { beforeAction?.Invoke(); string myAddress = GetMyAddress().ToString(); rakPeer.CloseConnection(new AddressOrGUID(new SystemAddress(_coordinatorAddress.Address, _coordinatorAddress.Port)), true); isThreadRunning = false; rakPeer.Shutdown(10); RakPeerInterface.DestroyInstance(rakPeer); RaknetExtension.WriteWarning(string.Format("UdpProxyServer停止了:{0}", myAddress)); }
internal RakNetConnection(RakNetGUID guid, long id, RakPeerInterface peer, Action <RakNetConnection> closeAction) { ConnectionDate = DateTime.UtcNow; LastActivityDate = DateTime.UtcNow; Id = id; _guid = guid; _rakPeer = peer; _closeAction = closeAction; State = Stormancer.Core.ConnectionState.Connecting; }
public void ConnectFac() { if (!NATNetworkManager_PHP.connectedToFac) { rakPeer = RakPeerInterface.GetInstance(); //rakPeer = natPunchthroughClient.GetRakPeerInterface(); //natPunchthroughClient = null; //facilitatorSystemAddress = null; StopCoroutine("connectToNATFacilitator"); StartCoroutine("connectToNATFacilitator"); } }
public void Add(RakPeerInterface recipient, IProtocolProcessor processor) { IDictionary<string, IProtocolProcessor> processors; if (processorsByRecipient.TryGetValue(recipient, out processors)) { processors.Add(processor.ProtocolName, processor); } else { processors = new Dictionary<string, IProtocolProcessor>(); processors.Add(processor.ProtocolName, processor); processorsByRecipient.Add(recipient, processors); } }
public void Dispose() { if (_scheduledTransportLoop != null) { _scheduledTransportLoop.Dispose(); if (_peer != null) { if (_peer.IsActive()) { _peer.Shutdown(1000); } RakPeerInterface.DestroyInstance(_peer); } IsRunning = false; _logger.Info("transports.raknet", "Stopped raknet server."); } }
private void OnDisconnection(RakNet.Packet packet, RakPeerInterface server, string reason) { _logger.Trace("transports.raknet", "{0} disconnected", packet.systemAddress); var c = RemoveConnection(packet.guid); server.DeallocatePacket(packet); _handler.CloseConnection(c, reason); c.RaiseConnectionClosed(reason); var action = ConnectionClosed; if (action != null) { action(c); } }
private void OnConnection(RakNet.Packet packet, RakPeerInterface server) { logger.Trace("Connected to endpoint {0}", packet.systemAddress); var c = CreateNewConnection(packet.guid, server); server.DeallocatePacket(packet); _handler.NewConnection(c); var action = ConnectionOpened; if (action != null) { action(c); } c.SendSystem((byte)MessageIDTypes.ID_CONNECTION_RESULT, s => s.Write(BitConverter.GetBytes(c.Id), 0, 8)); }
public int Start(out string ip, out ushort port, ushort maxConnections) { this.server = RakPeer.GetInstance(); this.server.SetMaximumIncomingConnections(maxConnections); StartupResult result = this.server.Startup(maxConnections, new SocketDescriptor(), 1); SystemAddress adr = this.server.GetMyBoundAddress(); ip = adr.ToString(false); port = adr.GetPort(); Log.WriteLine(string.Format("监听server {0}:{1}", ip, port)); if (result != StartupResult.RAKNET_STARTED) { Log.WriteLine(string.Format("服务器启动失败 retCode:{0}", result)); return(-1); } return(0); }
private void Initialize(ushort?serverPort, ushort maxConnections) { try { IsRunning = true; _logger.Info("transports.raknet", "starting raknet transport " + _type); _peer = RakPeerInterface.GetInstance(); var socketDescriptor = serverPort.HasValue ? new SocketDescriptor(serverPort.Value, null) : new SocketDescriptor(); var startupResult = _peer.Startup(maxConnections, socketDescriptor, 1); if (startupResult != StartupResult.RAKNET_STARTED) { throw new InvalidOperationException("Couldn't start raknet peer :" + startupResult); } _peer.SetMaximumIncomingConnections(maxConnections); } catch (Exception e) { throw new InvalidOperationException("Failed to initialize Raknet", e); } }
static void ProcessMessage(RakPeerInterface peer, RakNet.Packet packet) { if (packet != null) { if (packet.data[0] == (byte)(FT_MessageTypes.ID_SERVER_LOGIN)) { BitStream receiveBitStream = new BitStream(); receiveBitStream.Write(packet.data, packet.length); receiveBitStream.IgnoreBytes(2); FT_UnitData data = new FT_UnitData(); data.Serialize(false, receiveBitStream); Log.Debug(" data.nGrid_x: " + data.nGrid_x); BitStream writeBitStream = new BitStream(); writeBitStream.Write((byte)FT_MessageTypes.ID_SERVER_LOGIN); writeBitStream.Write((byte)FT_MessageTypesNode.NODE_FT_TEST1); data.Serialize(true, writeBitStream); uint sendLength = peer.Send(writeBitStream, PacketPriority.HIGH_PRIORITY, PacketReliability.RELIABLE_ORDERED, (char)0, packet.systemAddress, false); Log.Debug("SendLength = " + sendLength); } } }
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); }
/// <summary> /// 彻底关掉raknet /// </summary> public void ShutDown() { Debug.LogFormat("=====Client ShutDown 1: {0} IP:{1}", ClientName, ServerIP); if (mClient != null && mClient.IsActive() && !string.IsNullOrEmpty(ServerIP) && !(m_serverAddress == null)) { Debug.LogFormat("DisConnect Server[{0}]===2=>[{1}].", this.ClientName, this.ServerIP); //Debug.Log("mClient.CloseConnection 被调用"); mClient.CloseConnection(m_serverAddress, true); } Debug.LogFormat("=====Client ShutDown 2: {0} IP:{1}", ClientName, ServerIP); if (mClient != null) { //Debug.Log("mClient.Shutdown 被调用"); mClient.Shutdown(300); RakPeerInterface.DestroyInstance(mClient); mClient = null; } IsStartUp = false; IsConnectedServer = false; IsConnecting = false; Debug.LogFormat("=====Client ShutDown 3: {0} IP:{1}", ClientName, ServerIP); }
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); } }
public RpcBinder(RakPeerInterface recipient, IProcessorRegistry registry, IProtocolProcessor processor) { this.recipient = recipient; this.registry = registry; this.processor = processor; }
public Connection(RakPeerInterface rakPeer, bool connectionCompleted) { RakPeer = rakPeer; ConnectionCompleted = connectionCompleted; }
public void Startup(ushort maxConnections, int threadSleepTimer, ushort port, PluginInterface[] plugins) { rakPeerInterface = RakNetworkFactory.GetRakPeerInterface(); foreach (PluginInterface plugin in plugins) { RakPeerInterface.AttachPlugin(plugin); } // Initialize the peer SocketDescriptor socketDescriptor = new SocketDescriptor(port, string.Empty); RakPeerInterface.Startup(maxConnections, threadSleepTimer, new SocketDescriptor[] {socketDescriptor}, 1); RakPeerInterface.SetMaximumIncomingConnections(maxConnections); binder = new RpcBinder(RakPeerInterface, registry, processorLocator.Processor); binder.Bind(); }
public IProtocolProcessor GetProcessor(RakPeerInterface recipient, string protocolName) { return processorsByRecipient[recipient][protocolName]; }
public static void DestroyRakPeerInterface(RakPeerInterface i) { RakNetPINVOKE.RakNetworkFactory_DestroyRakPeerInterface(RakPeerInterface.getCPtr(i)); }
static int Main(string[] args) { char ch; string userInput; rakPeer = RakNetworkFactory.GetRakPeerInterface(); rakPeer.AttachPlugin(replicaManager); rakPeer.SetNetworkIDManager(networkIDManager); replicaManager.SetAutoParticipateNewConnections(true); replicaManager.SetAutoConstructToNewParticipants(true); replicaManager.SetAutoSerializeInScope(true); replicaManager.SetReceiveConstructionCB(IntPtr.Zero, ConstructionCB); replicaManager.SetDownloadCompleteCB(IntPtr.Zero, SendDownloadCompleteCB, IntPtr.Zero, ReceiveDownloadCompleteCB); StringTable.Instance().AddString("Player", true); StringTable.Instance().AddString("Monster", true); Console.Write("Demonstration of ReplicaManager for client / server\n"); Console.Write("The replica manager provides a framework to make it easier to synchronize\n"); Console.Write("object creation, destruction, and member object updates\n"); Console.Write("Difficulty: Intermediate\n\n"); Console.Write("Run as (s)erver or (c)lient? "); userInput = Console.ReadLine(); if (userInput[0] == 's' || userInput[0] == 'S') { isServer = true; SocketDescriptor socketDescriptor = new SocketDescriptor(60000, string.Empty); rakPeer.Startup(8, 0, new SocketDescriptor[] { socketDescriptor }, 1); rakPeer.SetMaximumIncomingConnections(8); Console.Write("Server started.\n"); } else { isServer = false; SocketDescriptor socketDescriptor = new SocketDescriptor(); rakPeer.Startup(1, 0, new SocketDescriptor[] { socketDescriptor }, 1); Console.Write("Enter IP to connect to: "); userInput = Console.ReadLine(); if (userInput.Equals(string.Empty)) { userInput = "127.0.0.1"; Console.Write("{0}\n", userInput); } if (!rakPeer.Connect(userInput, 60000, string.Empty, 0)) { Console.Write("Connect call failed!\n"); return 1; } Console.Write("Connecting...\n"); } // The network ID manager will automatically index pointers of object instance NetworkIDObject if // SetIsNetworkIDAuthority is called with true. Otherwise, it will rely on another system setting the IDs networkIDManager.SetIsNetworkIDAuthority(isServer); Console.Write("Commands:\n(Q)uit\n(Space) Show status\n(R)andomize health and position\n"); if (isServer) { Console.Write("Toggle (M)onster\nToggle (p)layer\n"); Console.Write("Toggle (S)cope of player\n"); } Packet p; while (true) { p = rakPeer.Receive(); while (p != null) { byte[] data = p.data; // The access to data member had better reduce it. Copying occurs by this. if (data[0] == RakNetBindings.ID_DISCONNECTION_NOTIFICATION || data[0] == RakNetBindings.ID_CONNECTION_LOST) { if (isServer) { Console.Write("Server connection lost. Deleting objects\n"); if (monster != null) { monster.Dispose(); } if (player != null) { player.Dispose(); } } } rakPeer.DeallocatePacket(p); p = rakPeer.Receive(); } if (_kbhit() != 0) { ch = Console.ReadKey(true).KeyChar; if (ch == 'q' || ch == 'Q') { Console.Write("Quitting.\n"); break; } else if (ch == ' ') ShowStatus(monster, player); else if (ch == 'r' || ch == 'R') { if (player != null) { player.health = (int)RakNetBindings.randomMT(); player.position = (int)RakNetBindings.randomMT(); replicaManager.SignalSerializeNeeded(player.replica, RakNetBindings.UNASSIGNED_SYSTEM_ADDRESS, true); } if (monster != null) { monster.health = (int)RakNetBindings.randomMT(); monster.position = (int)RakNetBindings.randomMT(); replicaManager.SignalSerializeNeeded(monster.replica, RakNetBindings.UNASSIGNED_SYSTEM_ADDRESS, true); } Console.Write("Randomized player and monster health and position\n"); ShowStatus(monster, player); } else if (isServer) { if (ch == 'm' || ch == 'M') { if (monster == null) { Console.Write("Creating monster\n"); monster = new Monster(); } else { monster.Dispose(); Console.Write("Deleted monster\n"); monster = null; } } else if (ch == 'p' || ch == 'P') { if (player == null) { Console.Write("Creating player\n"); player = new Player(); } else { player.Dispose(); Console.Write("Deleted player\n"); player = null; } } else if (ch == 's' || ch == 'S') { if (player != null) { bool currentScope; currentScope = replicaManager.IsInScope(player.replica, rakPeer.GetSystemAddressFromIndex(0)); if (currentScope == false) Console.Write("Setting scope for player to true for all remote systems.\n"); else Console.Write("Setting scope for player to false for all remote systems.\n"); replicaManager.SetScope(player.replica, !currentScope, RakNetBindings.UNASSIGNED_SYSTEM_ADDRESS, true); } else { Console.Write("No player to set scope for\n"); } } } } System.Threading.Thread.Sleep(30); } if (monster != null) monster.Dispose(); if (player != null) player.Dispose(); RakNetworkFactory.DestroyRakPeerInterface(rakPeer); return 1; }