コード例 #1
0
        public void NatIntroduce(
            NetEndPoint hostInternal,
            NetEndPoint hostExternal,
            NetEndPoint clientInternal,
            NetEndPoint clientExternal,
            string additionalInfo)
        {
            NetDataWriter dw = new NetDataWriter();

            //First packet (server)
            //send to client
            dw.Put(ClientByte);
            dw.Put(hostInternal);
            dw.Put(hostExternal);
            dw.Put(additionalInfo, MaxTokenLength);

            _netBase.SendRaw(NetPacket.CreateRawPacket(PacketProperty.NatIntroduction, dw), clientExternal);

            //Second packet (client)
            //send to server
            dw.Reset();
            dw.Put(HostByte);
            dw.Put(clientInternal);
            dw.Put(clientExternal);
            dw.Put(additionalInfo, MaxTokenLength);

            _netBase.SendRaw(NetPacket.CreateRawPacket(PacketProperty.NatIntroduction, dw), hostExternal);
        }
コード例 #2
0
ファイル: NtpSyncModule.cs プロジェクト: RevenantX/LiteNetLib
 public NtpSyncModule(string ntpServer)
 {
     _ntpEndPoint = new NetEndPoint(ntpServer, 123);
     _socket = new NetSocket(OnMessageReceived);
     _socket.Bind(0);
     SyncedTime = null;
 }
コード例 #3
0
ファイル: BroadcastTest.cs プロジェクト: RevenantX/LiteNetLib
 public void OnNetworkReceiveUnconnected(NetEndPoint remoteEndPoint, NetDataReader reader, UnconnectedMessageType messageType)
 {
     Console.WriteLine("[Server] ReceiveUnconnected {0}. From: {1}. Data: {2}", messageType, remoteEndPoint, reader.GetString(100));
     NetDataWriter wrtier = new NetDataWriter();
     wrtier.Put("SERVER DISCOVERY RESPONSE :)");
     Server.SendDiscoveryResponse(wrtier, remoteEndPoint);
 }
コード例 #4
0
ファイル: BroadcastTest.cs プロジェクト: RevenantX/LiteNetLib
 public void OnNetworkReceiveUnconnected(NetEndPoint remoteEndPoint, NetDataReader reader, UnconnectedMessageType messageType)
 {
     Console.WriteLine("[Client] ReceiveUnconnected {0}. From: {1}. Data: {2}", messageType, remoteEndPoint, reader.GetString(100));
     if (messageType == UnconnectedMessageType.DiscoveryResponse)
     {
         Client.Connect(remoteEndPoint);
     }
 }
コード例 #5
0
ファイル: GameServer.cs プロジェクト: RevenantX/LiteNetLib
 public void OnNetworkReceiveUnconnected(NetEndPoint remoteEndPoint, NetDataReader reader, UnconnectedMessageType messageType)
 {
     if (messageType == UnconnectedMessageType.DiscoveryRequest)
     {
         Debug.Log("[SERVER] Received discovery request. Send discovery response");
         _netServer.SendDiscoveryResponse(new byte[] {1}, remoteEndPoint);
     }
 }
コード例 #6
0
ファイル: GameClient.cs プロジェクト: RevenantX/LiteNetLib
 public void OnNetworkReceiveUnconnected(NetEndPoint remoteEndPoint, NetDataReader reader, UnconnectedMessageType messageType)
 {
     if (messageType == UnconnectedMessageType.DiscoveryResponse && _netClient.Peer == null)
     {
         Debug.Log("[CLIENT] Received discovery response. Connecting to: " + remoteEndPoint);
         _netClient.Connect(remoteEndPoint);
     }
 }
コード例 #7
0
ファイル: NtpSyncModule.cs プロジェクト: RevenantX/LiteNetLib
        private void OnMessageReceived(byte[] data, int length, int errorCode, NetEndPoint remoteEndPoint)
        {
            if (errorCode != 0)
            {
                _waiter.Set();
                return;
            }

            ulong intPart = (ulong)data[40] << 24 | (ulong)data[41] << 16 | (ulong)data[42] << 8 | (ulong)data[43];
            ulong fractPart = (ulong)data[44] << 24 | (ulong)data[45] << 16 | (ulong)data[46] << 8 | (ulong)data[47];

            var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
            SyncedTime = (new DateTime(1900, 1, 1)).AddMilliseconds((long)milliseconds);

            _waiter.Set();
        }
コード例 #8
0
ファイル: NetSocket.cs プロジェクト: RevenantX/LiteNetLib
        private void ReceiveLogic(object state)
        {
            Socket socket = (Socket)state;
            EndPoint bufferEndPoint = new IPEndPoint(socket.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0);
            NetEndPoint bufferNetEndPoint = new NetEndPoint((IPEndPoint)bufferEndPoint);
            byte[] receiveBuffer = new byte[NetConstants.PacketSizeLimit];

            while (_running)
            {
                //wait for data
                if (!socket.Poll(SocketReceivePollTime, SelectMode.SelectRead))
                {
                    continue;
                }

                int result;

                //Reading data
                try
                {
                    result = socket.ReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ref bufferEndPoint);
                    if (!bufferNetEndPoint.EndPoint.Equals(bufferEndPoint))
                    {
                        bufferNetEndPoint = new NetEndPoint((IPEndPoint)bufferEndPoint);
                    }
                }
                catch (SocketException ex)
                {
                    if (ex.SocketErrorCode == SocketError.ConnectionReset ||
                        ex.SocketErrorCode == SocketError.MessageSize)
                    {
                        //10040 - message too long
                        //10054 - remote close (not error)
                        //Just UDP
                        NetUtils.DebugWrite(ConsoleColor.DarkRed, "[R] Ingored error: {0} - {1}", ex.ErrorCode, ex.ToString() );
                        continue;
                    }
                    NetUtils.DebugWriteError("[R]Error code: {0} - {1}", ex.ErrorCode, ex.ToString());
                    _onMessageReceived(null, 0, (int)ex.SocketErrorCode, bufferNetEndPoint);
                    continue;
                }

                //All ok!
                NetUtils.DebugWrite(ConsoleColor.Blue, "[R]Recieved data from {0}, result: {1}", bufferNetEndPoint.ToString(), result);
                _onMessageReceived(receiveBuffer, result, 0, bufferNetEndPoint);
            }
        }
コード例 #9
0
        void INatPunchListener.OnNatIntroductionRequest(NetEndPoint localEndPoint, NetEndPoint remoteEndPoint, string token)
        {
            WaitPeer wpeer;
            if (_waitingPeers.TryGetValue(token, out wpeer))
            {
                if (wpeer.InternalAddr.Equals(localEndPoint) &&
                    wpeer.ExternalAddr.Equals(remoteEndPoint))
                {
                    wpeer.Refresh();
                    return;
                }

                Console.WriteLine("Wait peer found, sending introduction...");

                //found in list - introduce client and host to eachother
                Console.WriteLine(
                    "host - i({0}) e({1})\nclient - i({2}) e({3})",
                    wpeer.InternalAddr,
                    wpeer.ExternalAddr,
                    localEndPoint,
                    remoteEndPoint);

                _puncher.NatPunchModule.NatIntroduce(
                    wpeer.InternalAddr, // host internal
                    wpeer.ExternalAddr, // host external
                    localEndPoint, // client internal
                    remoteEndPoint, // client external
                    token // request token
                    );

                //Clear dictionary
                _waitingPeers.Remove(token);
            }
            else
            {
                Console.WriteLine("Wait peer created. i({0}) e({1})", localEndPoint, remoteEndPoint);
                _waitingPeers[token] = new WaitPeer(localEndPoint, remoteEndPoint);
            }
        }
コード例 #10
0
ファイル: NetBase.cs プロジェクト: romanov/LiteNetLib
 /// <summary>
 /// Send message without connection
 /// </summary>
 /// <param name="message">Raw data</param>
 /// <param name="remoteEndPoint">Packet destination</param>
 /// <returns>Operation result</returns>
 public bool SendUnconnectedMessage(byte[] message, NetEndPoint remoteEndPoint)
 {
     return(SendUnconnectedMessage(message, 0, message.Length, remoteEndPoint));
 }
コード例 #11
0
ファイル: NetBase.cs プロジェクト: romanov/LiteNetLib
 public bool SendDiscoveryResponse(NetDataWriter writer, NetEndPoint remoteEndPoint)
 {
     return(SendDiscoveryResponse(writer.Data, 0, writer.Length, remoteEndPoint));
 }
コード例 #12
0
        /// <summary>
        /// Connect to remote host
        /// </summary>
        /// <param name="address">Server IP or hostname</param>
        /// <param name="port">Server Port</param>
        /// <param name="connectionData">Additional data for remote peer</param>
        /// <returns>Null if connections limit reached, New NetPeer if new connection, Old NetPeer if already connected</returns>
        /// <exception cref="InvalidOperationException">Manager is not running. Call <see cref="Start()"/></exception>
        public NetPeer Connect(string address, int port, NetDataWriter connectionData)
        {
            var ep = new NetEndPoint(address, port);

            return(Connect(ep, connectionData));
        }
コード例 #13
0
        private void DataReceived(byte[] reusableBuffer, int count, NetEndPoint remoteEndPoint)
        {
#if STATS_ENABLED
            Statistics.PacketsReceived++;
            Statistics.BytesReceived += (uint)count;
#endif

            //Try read packet
            NetPacket packet = NetPacketPool.GetPacket(count, false);
            if (!packet.FromBytes(reusableBuffer, 0, count))
            {
                NetPacketPool.Recycle(packet);
                NetUtils.DebugWriteError("[NM] DataReceived: bad!");
                return;
            }

            //Check unconnected
            switch (packet.Property)
            {
            case PacketProperty.DiscoveryRequest:
                if (DiscoveryEnabled)
                {
                    var netEvent = CreateEvent(NetEventType.DiscoveryRequest);
                    netEvent.RemoteEndPoint = remoteEndPoint;
                    netEvent.DataReader.SetSource(packet.RawData, NetConstants.HeaderSize, count);
                    EnqueueEvent(netEvent);
                }
                return;

            case PacketProperty.DiscoveryResponse:
            {
                var netEvent = CreateEvent(NetEventType.DiscoveryResponse);
                netEvent.RemoteEndPoint = remoteEndPoint;
                netEvent.DataReader.SetSource(packet.RawData, NetConstants.HeaderSize, count);
                EnqueueEvent(netEvent);
            }
                return;

            case PacketProperty.UnconnectedMessage:
                if (UnconnectedMessagesEnabled)
                {
                    var netEvent = CreateEvent(NetEventType.ReceiveUnconnected);
                    netEvent.RemoteEndPoint = remoteEndPoint;
                    netEvent.DataReader.SetSource(packet.RawData, NetConstants.HeaderSize, count);
                    EnqueueEvent(netEvent);
                }
                return;

            case PacketProperty.NatIntroduction:
            case PacketProperty.NatIntroductionRequest:
            case PacketProperty.NatPunchMessage:
            {
                if (NatPunchEnabled)
                {
                    NatPunchModule.ProcessMessage(remoteEndPoint, packet);
                }
                return;
            }
            }

            //Check normal packets
            NetPeer netPeer;
            lock (_peers)
            {
                _peers.TryGetValue(remoteEndPoint, out netPeer);
            }
            if (netPeer != null &&
                netPeer.ConnectionState != ConnectionState.Disconnected)
            {
                switch (packet.Property)
                {
                case PacketProperty.Disconnect:
                    if (netPeer.ConnectionState == ConnectionState.InProgress ||
                        netPeer.ConnectionState == ConnectionState.Connected)
                    {
                        if (BitConverter.ToInt64(packet.RawData, 1) != netPeer.ConnectId)
                        {
                            //Old or incorrect disconnect
                            NetPacketPool.Recycle(packet);
                            return;
                        }

                        var netEvent = CreateEvent(NetEventType.Disconnect);
                        netEvent.Peer = netPeer;
                        netEvent.DataReader.SetSource(packet.RawData, 9, packet.Size);
                        netEvent.DisconnectReason = DisconnectReason.RemoteConnectionClose;
                        EnqueueEvent(netEvent);
                        //TODO: Very ugly fix
                        netPeer.Shutdown(null, 0, 0, true);
                    }
                    break;

                case PacketProperty.ShutdownOk:
                    if (netPeer.ConnectionState != ConnectionState.ShutdownRequested)
                    {
                        return;
                    }
                    netPeer.ProcessPacket(packet);
                    NetUtils.DebugWriteForce(ConsoleColor.Cyan, "[NM] ShutdownOK!");
                    break;

                case PacketProperty.ConnectAccept:
                    if (netPeer.ProcessConnectAccept(packet))
                    {
                        var connectEvent = CreateEvent(NetEventType.Connect);
                        connectEvent.Peer = netPeer;
                        EnqueueEvent(connectEvent);
                    }
                    NetPacketPool.Recycle(packet);
                    return;

                default:
                    netPeer.ProcessPacket(packet);
                    return;
                }
                return;
            }

            //Unacked shutdown
            if (packet.Property == PacketProperty.Disconnect)
            {
                byte[] data = { (byte)PacketProperty.ShutdownOk };
                SendRaw(data, 0, 1, remoteEndPoint);
                return;
            }

            if (packet.Property == PacketProperty.ConnectRequest && packet.Size >= 12)
            {
                int peersCount = GetPeersCount(ConnectionState.Connected | ConnectionState.InProgress);
                lock (_connectingPeers)
                {
                    if (_connectingPeers.Contains(remoteEndPoint))
                    {
                        return;
                    }
                    if (peersCount < _maxConnections)
                    {
                        int protoId = BitConverter.ToInt32(packet.RawData, 1);
                        if (protoId != NetConstants.ProtocolId)
                        {
                            NetUtils.DebugWrite(ConsoleColor.Cyan,
                                                "[NM] Peer connect reject. Invalid protocol ID: " + protoId);
                            return;
                        }

                        //Getting new id for peer
                        long connectionId = BitConverter.ToInt64(packet.RawData, 5);

                        // Read data and create request
                        var reader = new NetDataReader(null, 0, 0);
                        if (packet.Size > 12)
                        {
                            reader.SetSource(packet.RawData, 13, packet.Size);
                        }

                        _connectingPeers.Add(remoteEndPoint);
                        var netEvent = CreateEvent(NetEventType.ConnectionRequest);
                        netEvent.ConnectionRequest =
                            new ConnectionRequest(connectionId, remoteEndPoint, reader, OnConnectionSolved);
                        EnqueueEvent(netEvent);
                    }
                }
            }
        }
コード例 #14
0
 void INatPunchListener.OnNatIntroductionRequest(NetEndPoint localEndPoint, NetEndPoint remoteEndPoint, string token)
 {
     if(NatIntroductionRequest != null)
         NatIntroductionRequest(localEndPoint, remoteEndPoint, token);
 }
コード例 #15
0
ファイル: NetManager.cs プロジェクト: hafewa/MMORPG-Framework
        private void DataReceived(byte[] reusableBuffer, int count, NetEndPoint remoteEndPoint)
        {
#if STATS_ENABLED
            PacketsReceived++;
            BytesReceived += (uint)count;
#endif

            //Try get packet property
            PacketProperty property;
            if (!NetPacket.GetPacketProperty(reusableBuffer, out property))
            {
                return;
            }

            //Check unconnected
            switch (property)
            {
            case PacketProperty.DiscoveryRequest:
                if (DiscoveryEnabled)
                {
                    var netEvent = CreateEvent(NetEventType.DiscoveryRequest);
                    netEvent.RemoteEndPoint = remoteEndPoint;
                    netEvent.DataReader.SetSource(NetPacket.GetUnconnectedData(reusableBuffer, count));
                    EnqueueEvent(netEvent);
                }
                return;

            case PacketProperty.DiscoveryResponse:
            {
                var netEvent = CreateEvent(NetEventType.DiscoveryResponse);
                netEvent.RemoteEndPoint = remoteEndPoint;
                netEvent.DataReader.SetSource(NetPacket.GetUnconnectedData(reusableBuffer, count));
                EnqueueEvent(netEvent);
            }
                return;

            case PacketProperty.UnconnectedMessage:
                if (UnconnectedMessagesEnabled)
                {
                    var netEvent = CreateEvent(NetEventType.ReceiveUnconnected);
                    netEvent.RemoteEndPoint = remoteEndPoint;
                    netEvent.DataReader.SetSource(NetPacket.GetUnconnectedData(reusableBuffer, count));
                    EnqueueEvent(netEvent);
                }
                return;

            case PacketProperty.NatIntroduction:
            case PacketProperty.NatIntroductionRequest:
            case PacketProperty.NatPunchMessage:
            {
                if (NatPunchEnabled)
                {
                    NatPunchModule.ProcessMessage(remoteEndPoint, property, NetPacket.GetUnconnectedData(reusableBuffer, count));
                }
                return;
            }
            }

            //Check normal packets
            NetPacket packet;
            NetPeer   netPeer;

            //Check peers
            Monitor.Enter(_peers);
            int peersCount = _peers.Count;

            if (_peers.TryGetValue(remoteEndPoint, out netPeer))
            {
                Monitor.Exit(_peers);
                packet = netPeer.GetPacketFromPool(init: false);

                //Bad packet check
                if (!packet.FromBytes(reusableBuffer, 0, count))
                {
                    netPeer.Recycle(packet);
                    return;
                }

                //Send
                if (packet.Property == PacketProperty.Disconnect)
                {
                    if (BitConverter.ToInt64(packet.RawData, 1) != netPeer.ConnectId)
                    {
                        //Old or incorrect disconnect
                        netPeer.Recycle(packet);
                        return;
                    }

                    var netEvent = CreateEvent(NetEventType.Disconnect);
                    netEvent.Peer = netPeer;
                    netEvent.DataReader.SetSource(packet.RawData, 5, packet.RawData.Length - 5);
                    netEvent.DisconnectReason = DisconnectReason.RemoteConnectionClose;
                    EnqueueEvent(netEvent);
                    lock (_peersToRemove)
                    {
                        _peersToRemove.Enqueue(netPeer.EndPoint);
                    }
                    //do not recycle because no sense)
                }
                else if (packet.Property == PacketProperty.ConnectAccept)
                {
                    if (netPeer.ProcessConnectAccept(packet))
                    {
                        var connectEvent = CreateEvent(NetEventType.Connect);
                        connectEvent.Peer = netPeer;
                        EnqueueEvent(connectEvent);
                    }
                    netPeer.Recycle(packet);
                }
                else
                {
                    netPeer.ProcessPacket(packet);
                }
                return;
            }

            try
            {
                //Else add new peer
                packet = new NetPacket();
                if (!packet.FromBytes(reusableBuffer, 0, count))
                {
                    //Bad packet
                    return;
                }

                if (peersCount < _maxConnections && packet.Property == PacketProperty.ConnectRequest)
                {
                    int protoId = BitConverter.ToInt32(packet.RawData, 1);
                    if (protoId != NetConstants.ProtocolId)
                    {
                        NetUtils.DebugWrite(ConsoleColor.Cyan,
                                            "[NS] Peer connect reject. Invalid protocol ID: " + protoId);
                        return;
                    }

                    string peerKey = Encoding.UTF8.GetString(packet.RawData, 13, packet.RawData.Length - 13);
                    if (peerKey != _connectKey)
                    {
                        NetUtils.DebugWrite(ConsoleColor.Cyan, "[NS] Peer connect reject. Invalid key: " + peerKey);
                        return;
                    }

                    //Getting new id for peer
                    long connectionId = BitConverter.ToInt64(packet.RawData, 5);
                    //response with id
                    NetUtils.DebugWrite(ConsoleColor.Cyan, "[NS] Received peer connect request Id: {0}, EP: {1}",
                                        netPeer.ConnectId, remoteEndPoint);
                    netPeer = new NetPeer(this, remoteEndPoint, connectionId);

                    //clean incoming packet
                    netPeer.Recycle(packet);

                    _peers.Add(remoteEndPoint, netPeer);

                    var netEvent = CreateEvent(NetEventType.Connect);
                    netEvent.Peer = netPeer;
                    EnqueueEvent(netEvent);
                }
            }
            finally
            {
                Monitor.Exit(_peers);
            }
        }
コード例 #16
0
ファイル: NetPeerCollection.cs プロジェクト: senlace/shinkai
 public bool TryGetValue(NetEndPoint endPoint, out NetPeer peer)
 {
     return(_peersDict.TryGetValue(endPoint, out peer));
 }
コード例 #17
0
        public void SendNatIntroduceRequest(NetEndPoint masterServerEndPoint, string additionalInfo)
        {
            if (!_netBase.IsRunning)
                return;

            //prepare outgoing data
            NetDataWriter dw = new NetDataWriter();
            string networkIp = NetUtils.GetLocalIp(true);
            int networkPort = _netBase.LocalEndPoint.Port;
            NetEndPoint localEndPoint = new NetEndPoint(networkIp, networkPort);
            dw.Put(localEndPoint);
            dw.Put(additionalInfo, MaxTokenLength);

            //prepare packet
            _netBase.SendRaw(NetPacket.CreateRawPacket(PacketProperty.NatIntroductionRequest, dw), masterServerEndPoint);
        }
コード例 #18
0
ファイル: NetClient.cs プロジェクト: buybackoff/LiteNetLib
        protected override void ReceiveFromSocket(byte[] reusableBuffer, int count, NetEndPoint remoteEndPoint)
        {
            //Parse packet
            //Peer null when P2P connection packets
            NetPacket packet = _peer == null ? new NetPacket() : _peer.GetPacketFromPool(init: false);

            if (!packet.FromBytes(reusableBuffer, count))
            {
                if (_peer != null)
                {
                    _peer.Recycle(packet);
                }
                return;
            }

            //Check P2P mode
            if (PeerToPeerMode && packet.Property == PacketProperty.ConnectRequest)
            {
                NetUtils.DebugWrite(ConsoleColor.Cyan, "[NC] Received peer connect request");

                string peerKey = Encoding.UTF8.GetString(packet.RawData, 9, packet.RawData.Length - 9);
                if (peerKey != _connectKey)
                {
                    NetUtils.DebugWrite(ConsoleColor.Cyan, "[NC] Peer connect reject. Invalid key: " + peerKey);
                    return;
                }

                NetUtils.DebugWrite(ConsoleColor.Cyan, "[NC] Peer connect accepting");

                //Make initial packet and put id from received packet
                var connectPacket = NetPacket.CreateRawPacket(PacketProperty.ConnectAccept, 8);
                Buffer.BlockCopy(packet.RawData, 1, connectPacket, 1, 8);

                //Check our peer and create
                if (_peer == null)
                {
                    //Create connect id for proper connection
                    Connect(remoteEndPoint);
                }

                //Send raw
                SendRaw(connectPacket, remoteEndPoint);

                //clean incoming packet
                _peer.Recycle(packet);

                //We connected
                ProcessConnectAccept();

                return;
            }

            //Check peer
            if (_peer == null)
            {
                return;
            }

            //Check endpoint
            if (!_peer.EndPoint.Equals(remoteEndPoint))
            {
                NetUtils.DebugWriteForce(ConsoleColor.DarkCyan, "[NC] Bad EndPoint " + remoteEndPoint);
                return;
            }

            if (packet.Property == PacketProperty.Disconnect)
            {
                NetUtils.DebugWrite(ConsoleColor.Cyan, "[NC] Received disconnection");
                CloseConnection(true, "Received disconnection from server");
                return;
            }

            if (packet.Property == PacketProperty.ConnectAccept)
            {
                if (_connected)
                {
                    return;
                }

                //check connection id
                if (BitConverter.ToUInt64(packet.RawData, 1) != _connectId)
                {
                    return;
                }

                //connection things
                ProcessConnectAccept();
                return;
            }

            //Process income packet
            _peer.ProcessPacket(packet);
        }
コード例 #19
0
 internal void RemovePeer(NetEndPoint ep)
 {
     _peers.Remove(ep);
 }
コード例 #20
0
ファイル: NetClient.cs プロジェクト: buybackoff/LiteNetLib
 internal override void ProcessSendError(NetEndPoint remoteEndPoint, string errorMessage)
 {
     CloseConnection(true, "Send error: " + errorMessage);
     base.ProcessSendError(remoteEndPoint, errorMessage);
 }
コード例 #21
0
        public bool Bind(int port)
        {
            _udpSocketv4                   = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            _udpSocketv4.Blocking          = false;
            _udpSocketv4.ReceiveBufferSize = NetConstants.SocketBufferSize;
            _udpSocketv4.SendBufferSize    = NetConstants.SocketBufferSize;
            _udpSocketv4.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, NetConstants.SocketTTL);
#if !NETCORE
            _udpSocketv4.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DontFragment, true);
#endif

            try
            {
                _udpSocketv4.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
            }
            catch (SocketException e)
            {
                NetUtils.DebugWriteError("Broadcast error: {0}", e.ToString());
            }

            if (!BindSocket(_udpSocketv4, new IPEndPoint(IPAddress.Any, port)))
            {
                return(false);
            }
            _localEndPoint = new NetEndPoint((IPEndPoint)_udpSocketv4.LocalEndPoint);

            _running               = true;
            _threadv4              = new Thread(ReceiveLogic);
            _threadv4.Name         = "SocketThreadv4(" + port + ")";
            _threadv4.IsBackground = true;
            _threadv4.Start(_udpSocketv4);

            //Check IPv6 support
            if (!IPv6Support)
            {
                return(true);
            }

            //Use one port for two sockets
            port = _localEndPoint.Port;

            _udpSocketv6                   = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
            _udpSocketv6.Blocking          = false;
            _udpSocketv6.ReceiveBufferSize = NetConstants.SocketBufferSize;
            _udpSocketv6.SendBufferSize    = NetConstants.SocketBufferSize;

            if (BindSocket(_udpSocketv6, new IPEndPoint(IPAddress.IPv6Any, port)))
            {
                _localEndPoint = new NetEndPoint((IPEndPoint)_udpSocketv6.LocalEndPoint);

                try
                {
                    _udpSocketv6.SetSocketOption(
                        SocketOptionLevel.IPv6,
                        SocketOptionName.AddMembership,
                        new IPv6MulticastOption(MulticastAddressV6));
                }
                catch
                {
                    // Unity3d throws exception - ignored
                }

                _threadv6              = new Thread(ReceiveLogic);
                _threadv6.Name         = "SocketThreadv6(" + port + ")";
                _threadv6.IsBackground = true;
                _threadv6.Start(_udpSocketv6);
            }

            return(true);
        }
コード例 #22
0
ファイル: NetServer.cs プロジェクト: chwuchang/LiteNetLib
        protected override void ReceiveFromSocket(byte[] reusableBuffer, int count, NetEndPoint remoteEndPoint)
        {
            NetPacket packet;
            NetPeer   netPeer;

            //Check peers
            if (_peers.TryGetValue(remoteEndPoint, out netPeer))
            {
                packet = netPeer.GetPacketFromPool(init: false);

                //Bad packet check
                if (!packet.FromBytes(reusableBuffer, 0, count))
                {
                    netPeer.Recycle(packet);
                    return;
                }

                //Send
                if (packet.Property == PacketProperty.Disconnect)
                {
                    if (BitConverter.ToUInt64(packet.RawData, 1) != _peerConnectionIds[remoteEndPoint])
                    {
                        //Old or incorrect disconnect
                        netPeer.Recycle(packet);
                        return;
                    }
                    RemovePeer(netPeer);
                    var netEvent = CreateEvent(NetEventType.Disconnect);
                    netEvent.Peer             = netPeer;
                    netEvent.DisconnectReason = DisconnectReason.RemoteConnectionClose;
                    EnqueueEvent(netEvent);
                }
                else if (packet.Property == PacketProperty.ConnectRequest) //response with connect
                {
                    ulong lastId = _peerConnectionIds[remoteEndPoint];
                    ulong newId  = BitConverter.ToUInt64(packet.RawData, 1);
                    if (newId > lastId)
                    {
                        _peerConnectionIds[remoteEndPoint] = newId;
                    }

                    NetUtils.DebugWrite(ConsoleColor.Cyan, "ConnectRequest LastId: {0}, NewId: {1}, EP: {2}", lastId, newId, remoteEndPoint);
                    SendConnectAccept(netPeer, _peerConnectionIds[remoteEndPoint]);
                    netPeer.Recycle(packet);
                }
                else //throw out garbage packets
                {
                    netPeer.ProcessPacket(packet);
                }
                return;
            }

            //Else add new peer
            packet = new NetPacket();
            if (!packet.FromBytes(reusableBuffer, 0, count))
            {
                //Bad packet
                return;
            }

            if (_peers.Count < _maxClients && packet.Property == PacketProperty.ConnectRequest)
            {
                string peerKey = Encoding.UTF8.GetString(packet.RawData, 9, packet.RawData.Length - 9);
                if (peerKey != _connectKey)
                {
                    NetUtils.DebugWrite(ConsoleColor.Cyan, "[NS] Peer connect reject. Invalid key: " + peerKey);
                    return;
                }

                //Getting new id for peer
                netPeer = CreatePeer(remoteEndPoint);

                //response with id
                ulong connectionId = BitConverter.ToUInt64(packet.RawData, 1);
                NetUtils.DebugWrite(ConsoleColor.Cyan, "[NS] Received peer connect request Id: {0}, EP: {1}", connectionId, remoteEndPoint);


                SendConnectAccept(netPeer, connectionId);

                //clean incoming packet
                netPeer.Recycle(packet);

                lock (_peers)
                {
                    _peers.Add(remoteEndPoint, netPeer);
                    _peerConnectionIds.Add(remoteEndPoint, connectionId);
                }

                var netEvent = CreateEvent(NetEventType.Connect);
                netEvent.Peer = netPeer;
                EnqueueEvent(netEvent);
            }
        }
コード例 #23
0
ファイル: NetBase.cs プロジェクト: romanov/LiteNetLib
 internal bool SendRaw(byte[] message, NetEndPoint remoteEndPoint)
 {
     return(SendRaw(message, 0, message.Length, remoteEndPoint));
 }
コード例 #24
0
ファイル: NetPeerCollection.cs プロジェクト: senlace/shinkai
 public void Add(NetEndPoint endPoint, NetPeer peer)
 {
     _peersArray[Count] = peer;
     _peersDict.Add(endPoint, peer);
     Count++;
 }
コード例 #25
0
ファイル: NetBase.cs プロジェクト: romanov/LiteNetLib
 protected abstract void ReceiveFromSocket(byte[] reusableBuffer, int count, NetEndPoint remoteEndPoint);
コード例 #26
0
ファイル: NetPeerCollection.cs プロジェクト: senlace/shinkai
 public bool ContainsAddress(NetEndPoint endPoint)
 {
     return(_peersDict.ContainsKey(endPoint));
 }
コード例 #27
0
 private void HandleNatIntroductionRequest(NetEndPoint senderEndPoint, NetDataReader dr)
 {
     NetEndPoint localEp = dr.GetNetEndPoint();
     string token = dr.GetString(MaxTokenLength);
     lock (_requestEvents)
     {
         _requestEvents.Enqueue(new RequestEventData
         {
             LocalEndPoint = localEp,
             RemoteEndPoint = senderEndPoint,
             Token = token
         });
     }
 }
コード例 #28
0
        private void DataReceived(byte[] reusableBuffer, int count, NetEndPoint remoteEndPoint)
        {
#if STATS_ENABLED
            Statistics.PacketsReceived++;
            Statistics.BytesReceived += (uint)count;
#endif

            //Try read packet
            NetPacket packet = _netPacketPool.GetAndRead(reusableBuffer, 0, count);
            if (packet == null)
            {
                NetUtils.DebugWriteError("[NM] DataReceived: bad!");
                return;
            }

            //Check unconnected
            switch (packet.Property)
            {
            case PacketProperty.DiscoveryRequest:
                if (DiscoveryEnabled)
                {
                    var netEvent = CreateEvent(NetEventType.DiscoveryRequest);
                    netEvent.RemoteEndPoint = remoteEndPoint;
                    netEvent.DataReader.SetSource(packet.RawData, NetConstants.HeaderSize, count);
                    EnqueueEvent(netEvent);
                }
                return;

            case PacketProperty.DiscoveryResponse:
            {
                var netEvent = CreateEvent(NetEventType.DiscoveryResponse);
                netEvent.RemoteEndPoint = remoteEndPoint;
                netEvent.DataReader.SetSource(packet.RawData, NetConstants.HeaderSize, count);
                EnqueueEvent(netEvent);
            }
                return;

            case PacketProperty.UnconnectedMessage:
                if (UnconnectedMessagesEnabled)
                {
                    var netEvent = CreateEvent(NetEventType.ReceiveUnconnected);
                    netEvent.RemoteEndPoint = remoteEndPoint;
                    netEvent.DataReader.SetSource(packet.RawData, NetConstants.HeaderSize, count);
                    EnqueueEvent(netEvent);
                }
                return;

            case PacketProperty.NatIntroduction:
            case PacketProperty.NatIntroductionRequest:
            case PacketProperty.NatPunchMessage:
            {
                if (NatPunchEnabled)
                {
                    NatPunchModule.ProcessMessage(remoteEndPoint, packet);
                }
                return;
            }
            }

            //Check normal packets
            NetPeer netPeer;

            //Check peers
            Monitor.Enter(_peers);
            int peersCount = _peers.Count;

            if (_peers.TryGetValue(remoteEndPoint, out netPeer))
            {
                Monitor.Exit(_peers);
                //Send
                if (packet.Property == PacketProperty.Disconnect)
                {
                    if (BitConverter.ToInt64(packet.RawData, 1) != netPeer.ConnectId)
                    {
                        //Old or incorrect disconnect
                        _netPacketPool.Recycle(packet);
                        return;
                    }

                    var netEvent = CreateEvent(NetEventType.Disconnect);
                    netPeer.SetDisconnectedState();
                    netEvent.Peer = netPeer;
                    netEvent.DataReader.SetSource(packet.RawData, 9, packet.Size);
                    netEvent.DisconnectReason = DisconnectReason.RemoteConnectionClose;
                    EnqueueEvent(netEvent);

                    _peers.Remove(netPeer.EndPoint);
                    //do not recycle because no sense)
                }
                else if (packet.Property == PacketProperty.ConnectAccept)
                {
                    if (netPeer.ProcessConnectAccept(packet))
                    {
                        var connectEvent = CreateEvent(NetEventType.Connect);
                        connectEvent.Peer = netPeer;
                        EnqueueEvent(connectEvent);
                    }
                    _netPacketPool.Recycle(packet);
                }
                else
                {
                    netPeer.ProcessPacket(packet);
                }
                return;
            }

            try
            {
                if (peersCount < _maxConnections && packet.Property == PacketProperty.ConnectRequest)
                {
                    int protoId = BitConverter.ToInt32(packet.RawData, 1);
                    if (protoId != NetConstants.ProtocolId)
                    {
                        NetUtils.DebugWrite(ConsoleColor.Cyan,
                                            "[NM] Peer connect reject. Invalid protocol ID: " + protoId);
                        return;
                    }

                    string peerKey = Encoding.UTF8.GetString(packet.RawData, 13, packet.Size - 13);
                    if (peerKey != ConnectKey)
                    {
                        NetUtils.DebugWrite(ConsoleColor.Cyan, "[NM] Peer connect reject. Invalid key: " + peerKey);
                        return;
                    }

                    //Getting new id for peer
                    long connectionId = BitConverter.ToInt64(packet.RawData, 5);
                    //response with id
                    netPeer = new NetPeer(this, remoteEndPoint, connectionId);
                    NetUtils.DebugWrite(ConsoleColor.Cyan, "[NM] Received peer connect request Id: {0}, EP: {1}",
                                        netPeer.ConnectId, remoteEndPoint);

                    //clean incoming packet
                    _netPacketPool.Recycle(packet);

                    _peers.Add(remoteEndPoint, netPeer);

                    var netEvent = CreateEvent(NetEventType.Connect);
                    netEvent.Peer = netPeer;
                    EnqueueEvent(netEvent);
                }
            }
            finally
            {
                Monitor.Exit(_peers);
            }
        }
コード例 #29
0
        public int SendTo(byte[] data, int offset, int size, NetEndPoint remoteEndPoint, ref int errorCode)
        {
            try
            {
                var socket = _udpSocketv4;
                if (remoteEndPoint.EndPoint.AddressFamily == AddressFamily.InterNetworkV6 && IPv6Support)
                {
                    socket = _udpSocketv6;
                }

                int result;
#if WIN32 && UNSAFE
                var      handle            = socket.Handle;
                IntPtr[] fileDescriptorSet = { (IntPtr)1, handle };
                int      socketCount       = select(0, null, fileDescriptorSet, null, ref SendPollTime);
                if ((SocketError)socketCount == SocketError.SocketError)
                {
                    throw new SocketException(Marshal.GetLastWin32Error());
                }
                if ((int)fileDescriptorSet[0] == 0 || fileDescriptorSet[1] != handle)
                {
                    return(0);
                }
                unsafe
                {
                    fixed(byte *pinnedBuffer = data)
                    {
                        result = sendto(
                            handle,
                            pinnedBuffer + offset,
                            size,
                            SocketFlags.None,
                            remoteEndPoint.SocketAddr,
                            remoteEndPoint.SocketAddr.Length);
                    }
                }

                if ((SocketError)result == SocketError.SocketError)
                {
                    throw new SocketException(Marshal.GetLastWin32Error());
                }
#else
                if (!socket.Poll(SocketSendPollTime, SelectMode.SelectWrite))
                {
                    return(-1);
                }
                result = socket.SendTo(data, offset, size, SocketFlags.None, remoteEndPoint.EndPoint);
#endif

                NetUtils.DebugWrite(ConsoleColor.Blue, "[S]Send packet to {0}, result: {1}", remoteEndPoint.EndPoint, result);
                return(result);
            }
            catch (SocketException ex)
            {
                if (ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
                {
                    return(0);
                }
                if (ex.SocketErrorCode != SocketError.MessageSize)
                {
                    NetUtils.DebugWriteError("[S]" + ex);
                }

                errorCode = (int)ex.SocketErrorCode;
                return(-1);
            }
            catch (Exception ex)
            {
                NetUtils.DebugWriteError("[S]" + ex);
                return(-1);
            }
        }
コード例 #30
0
ファイル: UIManager.cs プロジェクト: vazgriz/Pong
 public void AddServer(LiteNetLib.NetEndPoint endpoint, string serverName)
 {
     Debug.Log(string.Format("{1} ({0})", endpoint, serverName));
 }
コード例 #31
0
ファイル: NetSocket.cs プロジェクト: achooley/LiteNetLib
        //Send to
        public int SendTo(byte[] data, NetEndPoint remoteEndPoint)
        {
            int errorCode = 0;

            return(SendTo(data, remoteEndPoint, ref errorCode));
        }
コード例 #32
0
ファイル: NetClient.cs プロジェクト: RevenantX/LiteNetLib
 /// <summary>
 /// Connect to NetServer or NetClient with PeerToPeerMode
 /// </summary>
 /// <param name="address">Server IP or hostname</param>
 /// <param name="port">Server Port</param>
 public void Connect(string address, int port)
 {
     //Create target endpoint
     NetEndPoint ep = new NetEndPoint(address, port);
     Connect(ep);
 }
コード例 #33
0
 /// <summary>
 /// Connect to remote host
 /// </summary>
 /// <param name="target">Server end point (ip and port)</param>
 /// <param name="key">Connection key</param>
 /// <returns>Null if connections limit reached, New NetPeer if new connection, Old NetPeer if already connected</returns>
 /// <exception cref="InvalidOperationException">Manager is not running. Call <see cref="Start()"/></exception>
 public NetPeer Connect(NetEndPoint target, string key)
 {
     return(Connect(target, NetDataWriter.FromString(key)));
 }
コード例 #34
0
ファイル: NetClient.cs プロジェクト: RevenantX/LiteNetLib
        public void Connect(NetEndPoint target)
        {
            if (!IsRunning)
            {
                throw new Exception("Client is not running");
            }
            if (_peer != null)
            {
                //Already connected
                return;
            }

            //Create connect id for proper connection
            _connectId = (ulong)DateTime.UtcNow.Ticks;
            NetUtils.DebugWrite(ConsoleColor.Cyan, "[CC] ConnectId: {0}", _connectId);

            //Create reliable connection
            _peer = CreatePeer(target);
            _peer.DebugTextColor = ConsoleColor.Yellow;

            //Create connection packet and send
            SendConnectRequest();

            _connectAttempts = 0;
        }
コード例 #35
0
ファイル: NetBase.cs プロジェクト: romanov/LiteNetLib
        protected void SocketRemovePeer(NetEndPoint ep)
        {
#if WINRT && !UNITY_EDITOR
            _socket.RemovePeer(ep);
#endif
        }
コード例 #36
0
ファイル: NetClient.cs プロジェクト: RevenantX/LiteNetLib
 internal override void ReceiveFromPeer(NetPacket packet, NetEndPoint remoteEndPoint)
 {
     NetUtils.DebugWrite(ConsoleColor.Cyan, "[NC] Received message");
     var netEvent = CreateEvent(NetEventType.Receive);
     netEvent.DataReader.SetSource(packet.GetPacketData());
     netEvent.Peer = _peer;
     netEvent.RemoteEndPoint = remoteEndPoint;
     EnqueueEvent(netEvent);
 }
コード例 #37
0
ファイル: NetBase.cs プロジェクト: romanov/LiteNetLib
 /// <summary>
 /// Send message without connection
 /// </summary>
 /// <param name="writer">Data serializer</param>
 /// <param name="remoteEndPoint">Packet destination</param>
 /// <returns>Operation result</returns>
 public bool SendUnconnectedMessage(NetDataWriter writer, NetEndPoint remoteEndPoint)
 {
     return(SendUnconnectedMessage(writer.Data, 0, writer.Length, remoteEndPoint));
 }
コード例 #38
0
ファイル: NetClient.cs プロジェクト: RevenantX/LiteNetLib
 internal override void ProcessSendError(NetEndPoint remoteEndPoint, int socketErrorCode)
 {
     CloseConnection(true, DisconnectReason.SocketSendError, socketErrorCode);
     base.ProcessSendError(remoteEndPoint, socketErrorCode);
 }
コード例 #39
0
ファイル: NetBase.cs プロジェクト: romanov/LiteNetLib
 public bool SendDiscoveryResponse(byte[] data, NetEndPoint remoteEndPoint)
 {
     return(SendDiscoveryResponse(data, 0, data.Length, remoteEndPoint));
 }
コード例 #40
0
ファイル: NetClient.cs プロジェクト: RevenantX/LiteNetLib
        protected override void ReceiveFromSocket(byte[] reusableBuffer, int count, NetEndPoint remoteEndPoint)
        {
            //Parse packet
            //Peer null when P2P connection packets
            NetPacket packet = _peer == null ? new NetPacket() : _peer.GetPacketFromPool(init: false);
            if (!packet.FromBytes(reusableBuffer, 0, count))
            {
                if(_peer != null)
                    _peer.Recycle(packet);
                return;
            }

            //Check P2P mode
            if (PeerToPeerMode && packet.Property == PacketProperty.ConnectRequest)
            {
                NetUtils.DebugWrite(ConsoleColor.Cyan, "[NC] Received peer connect request");

                string peerKey = Encoding.UTF8.GetString(packet.RawData, 9, packet.RawData.Length - 9);
                if (peerKey != _connectKey)
                {
                    NetUtils.DebugWrite(ConsoleColor.Cyan, "[NC] Peer connect reject. Invalid key: " + peerKey);
                    return;
                }

                NetUtils.DebugWrite(ConsoleColor.Cyan, "[NC] Peer connect accepting");

                //Make initial packet and put id from received packet
                var connectPacket = NetPacket.CreateRawPacket(PacketProperty.ConnectAccept, 8);
                Buffer.BlockCopy(packet.RawData, 1, connectPacket, 1, 8);

                //Check our peer and create
                if (_peer == null)
                {
                    //Create connect id for proper connection
                    Connect(remoteEndPoint);
                }

                //Send raw
                SendRaw(connectPacket, remoteEndPoint);

                //clean incoming packet
                _peer.Recycle(packet);

                //We connected
                ProcessConnectAccept();

                return;
            }

            //Check peer
            if (_peer == null)
            {
                return;
            }

            //Check endpoint 
            if (!_peer.EndPoint.Equals(remoteEndPoint))
            {
                NetUtils.DebugWriteForce(ConsoleColor.DarkCyan, "[NC] Bad EndPoint " + remoteEndPoint);
                return;
            }

            if (packet.Property == PacketProperty.Disconnect)
            {
                NetUtils.DebugWrite(ConsoleColor.Cyan, "[NC] Received disconnection");
                CloseConnection(true, DisconnectReason.RemoteConnectionClose, 0);
                return;
            }

            if (packet.Property == PacketProperty.ConnectAccept)
            {
                if (_connected)
                {
                    return;
                }

                //check connection id
                if (BitConverter.ToUInt64(packet.RawData, 1) != _connectId)
                {
                    return;
                }

                //connection things
                ProcessConnectAccept();
                return;
            }

            //Process income packet
            _peer.ProcessPacket(packet);
        }
コード例 #41
0
ファイル: NetBase.cs プロジェクト: romanov/LiteNetLib
        private void DataReceived(byte[] reusableBuffer, int count, NetEndPoint remoteEndPoint)
        {
#if STATS_ENABLED
            PacketsReceived++;
            BytesReceived += (uint)count;
#endif

            //Try get packet property
            PacketProperty property;
            if (!NetPacket.GetPacketProperty(reusableBuffer, out property))
            {
                return;
            }

            //Check unconnected
            switch (property)
            {
            case PacketProperty.DiscoveryRequest:
                if (DiscoveryEnabled)
                {
                    var netEvent = CreateEvent(NetEventType.DiscoveryRequest);
                    netEvent.RemoteEndPoint = remoteEndPoint;
                    netEvent.DataReader.SetSource(NetPacket.GetUnconnectedData(reusableBuffer, count));
                    EnqueueEvent(netEvent);
                }
                return;

            case PacketProperty.DiscoveryResponse:
            {
                var netEvent = CreateEvent(NetEventType.DiscoveryResponse);
                netEvent.RemoteEndPoint = remoteEndPoint;
                netEvent.DataReader.SetSource(NetPacket.GetUnconnectedData(reusableBuffer, count));
                EnqueueEvent(netEvent);
            }
                return;

            case PacketProperty.UnconnectedMessage:
                if (UnconnectedMessagesEnabled)
                {
                    var netEvent = CreateEvent(NetEventType.ReceiveUnconnected);
                    netEvent.RemoteEndPoint = remoteEndPoint;
                    netEvent.DataReader.SetSource(NetPacket.GetUnconnectedData(reusableBuffer, count));
                    EnqueueEvent(netEvent);
                }
                return;

            case PacketProperty.NatIntroduction:
            case PacketProperty.NatIntroductionRequest:
            case PacketProperty.NatPunchMessage:
            {
                if (NatPunchEnabled)
                {
                    NatPunchModule.ProcessMessage(remoteEndPoint, property, NetPacket.GetUnconnectedData(reusableBuffer, count));
                }
                return;
            }
            }

            //other
            ReceiveFromSocket(reusableBuffer, count, remoteEndPoint);
        }
コード例 #42
0
 public WaitPeer(NetEndPoint internalAddr, NetEndPoint externalAddr)
 {
     Refresh();
     InternalAddr = internalAddr;
     ExternalAddr = externalAddr;
 }
コード例 #43
0
ファイル: NetBase.cs プロジェクト: romanov/LiteNetLib
 internal abstract void ReceiveFromPeer(NetPacket packet, NetEndPoint endPoint);
コード例 #44
0
ファイル: NetServer.cs プロジェクト: RevenantX/LiteNetLib
 internal override void ProcessSendError(NetEndPoint remoteEndPoint, int socketErrorCode)
 {
     NetPeer fromPeer;
     if (_peers.TryGetValue(remoteEndPoint, out fromPeer))
     {
         var netEvent = CreateEvent(NetEventType.Disconnect);
         netEvent.Peer = fromPeer;
         netEvent.DisconnectReason = DisconnectReason.SocketSendError;
         netEvent.AdditionalData = socketErrorCode;
         EnqueueEvent(netEvent);
         RemovePeer(fromPeer);
     }
     base.ProcessSendError(remoteEndPoint, socketErrorCode);
 }
コード例 #45
0
        private void HandleNatPunch(NetEndPoint senderEndPoint, NetDataReader dr)
        {
            byte fromHostByte = dr.GetByte();
            if (fromHostByte != HostByte && fromHostByte != ClientByte)
            {
                //garbage
                return;
            }

            //Read info
            string additionalInfo = dr.GetString(MaxTokenLength);
            NetUtils.DebugWrite(ConsoleColor.Green, "[NAT] punch received from {0} - additional info: {1}", senderEndPoint, additionalInfo);

            //Release punch success to client; enabling him to Connect() to msg.Sender if token is ok
            lock (_successEvents)
            {
                _successEvents.Enqueue(new SuccessEventData { TargetEndPoint = senderEndPoint, Token = additionalInfo });
            }
        }
コード例 #46
0
 public void OnNetworkError(NetEndPoint endPoint, int socketErrorCode)
 {
     Console.WriteLine("[Server] error: " + socketErrorCode);
 }
コード例 #47
0
        internal void ProcessMessage(NetEndPoint senderEndPoint, PacketProperty property, byte[] data)
        {
            NetDataReader dr = new NetDataReader(data);

            switch (property)
            {
                case PacketProperty.NatIntroductionRequest:
                    //We got request and must introduce
                    HandleNatIntroductionRequest(senderEndPoint, dr);
                    break;
                case PacketProperty.NatIntroduction:
                    //We got introduce and must punch
                    HandleNatIntroduction(dr);
                    break;
                case PacketProperty.NatPunchMessage:
                    //We got punch and can connect
                    HandleNatPunch(senderEndPoint, dr);
                    break;
            }
        }
コード例 #48
0
 public void OnNetworkError(NetEndPoint endPoint, int socketErrorCode)
 {
     Console.WriteLine("[Client] error! " + socketErrorCode);
 }
コード例 #49
0
 void INatPunchListener.OnNatIntroductionSuccess(NetEndPoint targetEndPoint, string token)
 {
     if (NatIntroductionSuccess != null)
         NatIntroductionSuccess(targetEndPoint, token);
 }
コード例 #50
0
        private void ReceiveLogic(object state)
        {
            Socket      socket            = (Socket)state;
            EndPoint    bufferEndPoint    = new IPEndPoint(socket.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0);
            NetEndPoint bufferNetEndPoint = new NetEndPoint((IPEndPoint)bufferEndPoint);

#if WIN32 && UNSAFE
            int       saddrSize         = 32;
            byte[]    prevAddress       = new byte[saddrSize];
            byte[]    socketAddress     = new byte[saddrSize];
            byte[]    addrBuffer        = new byte[16]; //IPAddress.IPv6AddressBytes
            var       sockeHandle       = socket.Handle;
            IntPtr[]  fileDescriptorSet = { (IntPtr)1, sockeHandle };
            TimeValue time = new TimeValue {
                Microseconds = SocketReceivePollTime
            };
#endif
            byte[] receiveBuffer = new byte[NetConstants.PacketSizeLimit];

            while (_running)
            {
                int result;

                //Reading data
                try
                {
#if WIN32 && UNSAFE
                    fileDescriptorSet[0] = (IntPtr)1;
                    fileDescriptorSet[1] = sockeHandle;
                    int socketCount = select(0, fileDescriptorSet, null, null, ref time);
                    if ((SocketError)socketCount == SocketError.SocketError)
                    {
                        throw new SocketException(Marshal.GetLastWin32Error());
                    }
                    if ((int)fileDescriptorSet[0] == 0 || fileDescriptorSet[1] != sockeHandle)
                    {
                        continue;
                    }

                    result = recvfrom(
                        sockeHandle,
                        receiveBuffer,
                        receiveBuffer.Length,
                        SocketFlags.None,
                        socketAddress,
                        ref saddrSize);
                    if ((SocketError)result == SocketError.SocketError)
                    {
                        throw new SocketException(Marshal.GetLastWin32Error());
                    }

                    bool recreate = false;
                    for (int i = 0; i < saddrSize; i++)
                    {
                        if (socketAddress[i] != prevAddress[i])
                        {
                            prevAddress[i] = socketAddress[i];
                            recreate       = true;
                        }
                    }
                    if (recreate)
                    {
                        if (socket.AddressFamily == AddressFamily.InterNetwork)
                        {
                            int  port    = (socketAddress[2] << 8 & 0xFF00) | socketAddress[3];
                            long address = (
                                (socketAddress[4] & 0x000000FF) |
                                (socketAddress[5] << 8 & 0x0000FF00) |
                                (socketAddress[6] << 16 & 0x00FF0000) |
                                (socketAddress[7] << 24)
                                ) & 0x00000000FFFFFFFF;
                            bufferNetEndPoint = new NetEndPoint(new IPEndPoint(address, port));
                        }
                        else
                        {
                            for (int i = 0; i < addrBuffer.Length; i++)
                            {
                                addrBuffer[i] = socketAddress[i + 8];
                            }
                            int  port  = (socketAddress[2] << 8 & 0xFF00) | (socketAddress[3]);
                            long scope = (socketAddress[27] << 24) +
                                         (socketAddress[26] << 16) +
                                         (socketAddress[25] << 8) +
                                         (socketAddress[24]);
                            bufferNetEndPoint = new NetEndPoint(new IPEndPoint(new IPAddress(addrBuffer, scope), port));
                        }
                    }
#else
                    if (!socket.Poll(SocketReceivePollTime, SelectMode.SelectRead))
                    {
                        continue;
                    }
                    result = socket.ReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ref bufferEndPoint);
                    if (!bufferNetEndPoint.EndPoint.Equals(bufferEndPoint))
                    {
                        bufferNetEndPoint = new NetEndPoint((IPEndPoint)bufferEndPoint);
                    }
#endif
                }
                catch (SocketException ex)
                {
                    if (ex.SocketErrorCode == SocketError.ConnectionReset ||
                        ex.SocketErrorCode == SocketError.MessageSize)
                    {
                        //10040 - message too long
                        //10054 - remote close (not error)
                        //Just UDP
                        NetUtils.DebugWrite(ConsoleColor.DarkRed, "[R] Ingored error: {0} - {1}", (int)ex.SocketErrorCode, ex.ToString());
                        continue;
                    }
                    NetUtils.DebugWriteError("[R]Error code: {0} - {1}", (int)ex.SocketErrorCode, ex.ToString());
                    _onMessageReceived(null, 0, (int)ex.SocketErrorCode, bufferNetEndPoint);

                    continue;
                }

                //All ok!
                NetUtils.DebugWrite(ConsoleColor.Blue, "[R]Received data from {0}, result: {1}", bufferNetEndPoint.ToString(), result);
                _onMessageReceived(receiveBuffer, result, 0, bufferNetEndPoint);
            }
        }
コード例 #51
0
ファイル: BroadcastTest.cs プロジェクト: RevenantX/LiteNetLib
 public void OnNetworkError(NetEndPoint endPoint, int error)
 {
     Console.WriteLine("[Client] error! " + error);
 }
コード例 #52
0
        /// <summary>
        /// Connect to remote host
        /// </summary>
        /// <param name="address">Server IP or hostname</param>
        /// <param name="port">Server Port</param>
        /// <param name="key">Connection key</param>
        /// <returns>Null if connections limit reached, New NetPeer if new connection, Old NetPeer if already connected</returns>
        /// <exception cref="InvalidOperationException">Manager is not running. Call <see cref="Start()"/></exception>
        public NetPeer Connect(string address, int port, string key)
        {
            var ep = new NetEndPoint(address, port);

            return(Connect(ep, key));
        }
コード例 #53
0
ファイル: NetServer.cs プロジェクト: RevenantX/LiteNetLib
 internal override void ReceiveFromPeer(NetPacket packet, NetEndPoint remoteEndPoint)
 {
     NetPeer fromPeer;
     if (_peers.TryGetValue(remoteEndPoint, out fromPeer))
     {
         var netEvent = CreateEvent(NetEventType.Receive);
         netEvent.Peer = fromPeer;
         netEvent.RemoteEndPoint = fromPeer.EndPoint;
         netEvent.DataReader.SetSource(packet.GetPacketData());
         EnqueueEvent(netEvent);
     }
 }
コード例 #54
0
 internal override void ProcessSendError(NetEndPoint remoteEndPoint, int socketErrorCode)
 {
     CloseConnection(true, DisconnectReason.SocketSendError, socketErrorCode);
     base.ProcessSendError(remoteEndPoint, socketErrorCode);
 }
コード例 #55
0
ファイル: NetServer.cs プロジェクト: RevenantX/LiteNetLib
        protected override void ReceiveFromSocket(byte[] reusableBuffer, int count, NetEndPoint remoteEndPoint)
        {
            NetPacket packet;
            NetPeer netPeer;

            //Check peers
            if (_peers.TryGetValue(remoteEndPoint, out netPeer))
            {
                packet = netPeer.GetPacketFromPool(init: false);

                //Bad packet check
                if (!packet.FromBytes(reusableBuffer, 0, count))
                {
                    netPeer.Recycle(packet);
                    return;
                }
                
                //Send
                if (packet.Property == PacketProperty.Disconnect)
                {
                    if (BitConverter.ToUInt64(packet.RawData, 1) != _peerConnectionIds[remoteEndPoint])
                    {
                        //Old or incorrect disconnect
                        netPeer.Recycle(packet);
                        return;
                    }
                    RemovePeer(netPeer);
                    var netEvent = CreateEvent(NetEventType.Disconnect);
                    netEvent.Peer = netPeer;
                    netEvent.DisconnectReason = DisconnectReason.RemoteConnectionClose;
                    EnqueueEvent(netEvent);
                }
                else if (packet.Property == PacketProperty.ConnectRequest) //response with connect
                {
                    ulong lastId = _peerConnectionIds[remoteEndPoint];
                    ulong newId = BitConverter.ToUInt64(packet.RawData, 1);
                    if (newId > lastId)
                    {
                        _peerConnectionIds[remoteEndPoint] = newId;
                    }
                    
                    NetUtils.DebugWrite(ConsoleColor.Cyan, "ConnectRequest LastId: {0}, NewId: {1}, EP: {2}", lastId, newId, remoteEndPoint);
                    SendConnectAccept(netPeer, _peerConnectionIds[remoteEndPoint]);
                    netPeer.Recycle(packet);
                }
                else //throw out garbage packets
                {
                    netPeer.ProcessPacket(packet);
                }
                return;
            }

            //Else add new peer
            packet = new NetPacket();
            if (!packet.FromBytes(reusableBuffer, 0, count))
            {
                //Bad packet
                return;
            }

            if (_peers.Count < _maxClients && packet.Property == PacketProperty.ConnectRequest)
            {
                string peerKey = Encoding.UTF8.GetString(packet.RawData, 9, packet.RawData.Length - 9);
                if (peerKey != _connectKey)
                {
                    NetUtils.DebugWrite(ConsoleColor.Cyan, "[NS] Peer connect reject. Invalid key: " + peerKey);
                    return;
                }

                //Getting new id for peer
                netPeer = CreatePeer(remoteEndPoint);

                //response with id
                ulong connectionId = BitConverter.ToUInt64(packet.RawData, 1);
                NetUtils.DebugWrite(ConsoleColor.Cyan, "[NS] Received peer connect request Id: {0}, EP: {1}", connectionId, remoteEndPoint);


                SendConnectAccept(netPeer, connectionId);

                //clean incoming packet
                netPeer.Recycle(packet);

                lock (_peers)
                {
                    _peers.Add(remoteEndPoint, netPeer);
                    _peerConnectionIds.Add(remoteEndPoint, connectionId);
                }

                var netEvent = CreateEvent(NetEventType.Connect);
                netEvent.Peer = netPeer;
                EnqueueEvent(netEvent);
            }
        }
コード例 #56
0
 void INatPunchListener.OnNatIntroductionSuccess(NetEndPoint targetEndPoint, string token)
 {
     //Ignore we are server
 }
コード例 #57
0
 public void OnNetworkReceiveUnconnected(NetEndPoint remoteEndPoint, NetDataReader reader, UnconnectedMessageType messageType)
 {
     Console.WriteLine("[Server] ReceiveUnconnected: {0}", reader.GetString(100));
 }
コード例 #58
0
ファイル: NetSocket.cs プロジェクト: DanisJoyal/LiteNetLib
        public bool Bind(IPAddress addressIPv4, IPAddress addressIPv6, int port, bool reuseAddress, bool enableIPv4, bool enableIPv6)
        {
            if (enableIPv4)
            {
                _udpSocketv4                   = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                _udpSocketv4.Blocking          = false;
                _udpSocketv4.ReceiveBufferSize = NetConstants.SocketBufferSize;
                _udpSocketv4.SendBufferSize    = NetConstants.SocketBufferSize;
                _udpSocketv4.Ttl               = NetConstants.SocketTTL;
                if (reuseAddress)
                {
                    _udpSocketv4.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                }
#if !NETCORE
                _udpSocketv4.DontFragment = true;
#endif
                try
                {
                    _udpSocketv4.EnableBroadcast = true;
                }
                catch (SocketException e)
                {
                    NetUtils.DebugWriteError("Broadcast error: {0}", e.ToString());
                }

                if (!BindSocket(_udpSocketv4, new IPEndPoint(addressIPv4, port)))
                {
                    return(false);
                }
                LocalPort = ((IPEndPoint)_udpSocketv4.LocalEndPoint).Port;

                _bufferEndPointv4    = new IPEndPoint(_udpSocketv4.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0);
                _bufferNetEndPointv4 = new NetEndPoint((IPEndPoint)_bufferEndPointv4);
            }

            //Check IPv6 support
            if (!IPv6Support || enableIPv6 == false)
            {
                return(true);
            }

            _udpSocketv6                   = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
            _udpSocketv6.Blocking          = false;
            _udpSocketv6.ReceiveBufferSize = NetConstants.SocketBufferSize;
            _udpSocketv6.SendBufferSize    = NetConstants.SocketBufferSize;
            //_udpSocketv6.Ttl = NetConstants.SocketTTL;
            if (reuseAddress)
            {
                _udpSocketv6.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            }

            //Use one port for two sockets
            if (BindSocket(_udpSocketv6, new IPEndPoint(addressIPv6, LocalPort)))
            {
                try
                {
#if !ENABLE_IL2CPP
                    _udpSocketv6.SetSocketOption(
                        SocketOptionLevel.IPv6,
                        SocketOptionName.AddMembership,
                        new IPv6MulticastOption(MulticastAddressV6));
#endif
                }
                catch (Exception)
                {
                    // Unity3d throws exception - ignored
                }
            }

            _bufferEndPointv6    = new IPEndPoint(_udpSocketv4.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0);
            _bufferNetEndPointv6 = new NetEndPoint((IPEndPoint)_bufferEndPointv6);

            return(true);
        }
コード例 #59
0
            public void OnNetworkReceiveUnconnected(NetEndPoint remoteEndPoint, NetDataReader reader, UnconnectedMessageType messageType)
            {

            }
コード例 #60
0
ファイル: NetSocket.cs プロジェクト: DanisJoyal/LiteNetLib
        public void Receive(bool ipV6, byte[] receiveBuffer)
        {
            Socket      socket;
            EndPoint    bufferEndPoint;
            NetEndPoint bufferNetEndPoint;
            int         result;

            if (ipV6 == true)
            {
                socket            = _udpSocketv6;
                bufferEndPoint    = _bufferEndPointv6;
                bufferNetEndPoint = _bufferNetEndPointv6;
            }
            else
            {
                socket            = _udpSocketv4;
                bufferEndPoint    = _bufferEndPointv4;
                bufferNetEndPoint = _bufferNetEndPointv4;
            }

            while (true)
            {
                if (socket == null || socket.Available < 1)
                {
                    return;
                }

                //Reading data
                try
                {
                    result = socket.ReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ref bufferEndPoint);
                    if (!bufferNetEndPoint.EndPoint.Equals(bufferEndPoint))
                    {
                        bufferNetEndPoint = new NetEndPoint((IPEndPoint)bufferEndPoint);
                    }
                }
                catch (SocketException ex)
                {
                    if (ex.SocketErrorCode == SocketError.WouldBlock)
                    {
                        // Hiii! Increase buffer size
                        return;
                    }
                    if (ex.SocketErrorCode == SocketError.ConnectionReset ||
                        ex.SocketErrorCode == SocketError.MessageSize ||
                        ex.SocketErrorCode == SocketError.Interrupted)
                    {
                        //10040 - message too long
                        //10054 - remote close (not error)
                        //Just UDP
                        NetUtils.DebugWrite(ConsoleColor.DarkRed, "[R] Ingored error: {0} - {1}", (int)ex.SocketErrorCode, ex.ToString());
                        return;
                    }
                    NetUtils.DebugWriteError("[R]Error code: {0} - {1}", (int)ex.SocketErrorCode, ex.ToString());
                    _onMessageReceived(null, 0, (int)ex.SocketErrorCode, bufferNetEndPoint);

                    return;
                }

                //All ok!
                NetUtils.DebugWrite(ConsoleColor.Blue, "[R]Received data from {0}, result: {1}", bufferNetEndPoint.ToString(), result);
                _onMessageReceived(receiveBuffer, result, 0, bufferNetEndPoint);
            }
        }