/// <summary> /// Handles receiving packets. Should be called in a new Task to avoid blocking the main thread. /// </summary> public override void ReceiveLoop() { while (true) { // Wait to receive something on the socket. EndPoint sender = null; byte[] data = Receive(RecvBuffer, RecvBuffer.Length, out sender); // Invoke the data received event. IPEndPoint endPoint = sender as IPEndPoint; RawDataReceived?.Invoke(data, SEndPoint.Create(endPoint.Address, endPoint.Port)); } }
private void DispatchRawPacket(byte[] packet, SEndPoint sender) { // TODO: Implement support for multiple netevents in a single packet. // Convert the two byte identifier to a ushort. ushort id = BitConverter.ToUInt16(packet.SubArray(0, 2), 0); // Try to find the type in the registered types dictionary. Type packetType; if (TypeManager.TryGetTypeFromID(id, out packetType)) { NetworkEvent netEvent = new NetworkEvent(packet); } }
/// <summary> /// Starts the NetworkManager. /// </summary> /// <param name="socket"> The socket to use. </param> /// <param name="settings"> The settings used by the network manager. </param> /// <param name="mode"> The network mode to use. </param> public static void StartNetwork(NetSocket socket, NetworkSettings settings, NetworkMode mode) { if (IsStarted) { throw new InvalidOperationException("Cannot start NetworkManager: already started."); } coreSocket = socket; var address = NetUtils.GetLocalEndpoint(); var local = SEndPoint.Create(address.GetAddressBytes(), settings.Port); coreSocket.BindSocket(local); NetUtils.SetConnReset(coreSocket.Socket); // Run the receiving loop on a new Task. Task.Run(() => coreSocket.ReceiveLoop()); // TODO: Implement differed sending loop through Tick. netMode = mode; Settings = settings; IsStarted = true; }