Пример #1
0
 public void StartSearchBroadCasting(ServerFound cbServerFound, ServerNotFound cbServerNotFound, int port)
 {
     this.cbServerFound    = cbServerFound;
     this.cbServerNotFound = cbServerNotFound;
     StartBroadcasting();
     StartSearching();
 }
 void onServerFound(IPAddress address)
 {
     this.control.Invoke((MethodInvoker)(() =>
     {
         ServerFound?.Invoke(address);
     }));
 }
Пример #3
0
        public void StartFindingServer(int sendPort, int receivePort, ServerFound onServerFound)
        {
            StopFindingServer();

            _finding = true;

            _onServerFound = onServerFound;

            _reciveUdpClient = new UdpClient(receivePort);

            _sendUdpClient = new UdpClient();
            _sendUdpClient.EnableBroadcast = true;

            _broadcastIpEndPoint = new IPEndPoint(IPAddress.Broadcast, sendPort);

            StartReceivingServerReply();
            StartSendingServerRequest();
        }
Пример #4
0
        void NetworkThread()
        {
            sw = Stopwatch.StartNew();
            var listener = new EventBasedNetListener();

            client = new NetManager(listener)
            {
                UnconnectedMessagesEnabled = true,
                IPv6Enabled     = true,
                NatPunchEnabled = true,
                ChannelsCount   = 3
            };
            listener.NetworkReceiveUnconnectedEvent += (remote, msg, type) =>
            {
                if (type == UnconnectedMessageType.Broadcast)
                {
                    return;
                }
                if (msg.GetInt() == 0)
                {
                    lock (srvinfo)
                    {
                        foreach (var info in srvinfo)
                        {
                            if (info.EndPoint.Equals(remote))
                            {
                                var t = sw.ElapsedMilliseconds;
                                info.Ping = (int)(t - info.LastPingTime);
                                if (info.Ping < 0)
                                {
                                    info.Ping = 0;
                                }
                            }
                        }
                    }
                }
                else if (ServerFound != null)
                {
                    var info = new LocalServerInfo();
                    info.EndPoint       = remote;
                    info.Unique         = msg.GetInt();
                    info.Name           = msg.GetString();
                    info.Description    = msg.GetString();
                    info.DataVersion    = msg.GetString();
                    info.CurrentPlayers = msg.GetInt();
                    info.MaxPlayers     = msg.GetInt();
                    info.LastPingTime   = sw.ElapsedMilliseconds;
                    NetDataWriter writer = new NetDataWriter();
                    writer.Put(LNetConst.PING_MAGIC);
                    client.SendUnconnectedMessage(writer, remote);
                    lock (srvinfo)
                    {
                        bool add = true;
                        for (int i = 0; i < srvinfo.Count; i++)
                        {
                            if (srvinfo[i].Unique == info.Unique)
                            {
                                add = false;
                                //Prefer IPv6
                                if (srvinfo[i].EndPoint.AddressFamily != AddressFamily.InterNetwork &&
                                    info.EndPoint.AddressFamily == AddressFamily.InterNetwork)
                                {
                                    srvinfo[i].EndPoint = info.EndPoint;
                                }
                                break;
                            }
                        }
                        if (add)
                        {
                            srvinfo.Add(info);
                            mainThread.QueueUIThread(() => ServerFound?.Invoke(info));
                        }
                    }
                }
                msg.Recycle();
            };
            listener.NetworkReceiveEvent += (peer, reader, method) =>
            {
                try
                {
                    var packetCount = reader.GetByte(); //reliable packets can be merged
                    if (packetCount > 1)
                    {
                        FLLog.Debug("Net", $"Received {packetCount} merged packets");
                    }
                    for (int i = 0; i < packetCount; i++)
                    {
                        var pkt = Packets.Read(reader);
                        if (connecting)
                        {
                            if (pkt is AuthenticationPacket)
                            {
                                var auth = (AuthenticationPacket)pkt;
                                FLLog.Info("Net", "Authentication Packet Received");
                                if (auth.Type == AuthenticationKind.Token)
                                {
                                    FLLog.Info("Net", "Token");
                                    var str = reader.GetString();
                                    mainThread.QueueUIThread(() => AuthenticationRequired(str));
                                }
                                else if (auth.Type == AuthenticationKind.GUID)
                                {
                                    FLLog.Info("Net", "GUID");
                                    SendPacket(new AuthenticationReplyPacket()
                                    {
                                        Guid = this.UUID
                                    },
                                               PacketDeliveryMethod.ReliableOrdered);
                                }
                            }
                            else if (pkt is LoginSuccessPacket)
                            {
                                FLLog.Info("Client", "Login success");
                                connecting = false;
                            }
                            else
                            {
                                client.DisconnectAll();
                            }
                        }
                        else
                        {
                            packets.Enqueue(pkt);
                        }
                    }
                }
                catch (Exception e)
                {
                    FLLog.Error("Client", "Error reading packet");
                    client.DisconnectAll();
                }
            };
            listener.PeerDisconnectedEvent += (peer, info) =>
            {
                mainThread.QueueUIThread(() => { Disconnected?.Invoke(info.Reason.ToString()); });
            };
            client.Start();
            while (running)
            {
                if (Interlocked.Read(ref localPeerRequests) > 0)
                {
                    Interlocked.Decrement(ref localPeerRequests);
                    var dw = new NetDataWriter();
                    dw.Put(LNetConst.BROADCAST_KEY);
                    client.SendBroadcast(dw, LNetConst.DEFAULT_PORT);
                }
                //ping servers
                lock (srvinfo)
                {
                    foreach (var inf in srvinfo)
                    {
                        var nowMs = sw.ElapsedMilliseconds;
                        if (nowMs - inf.LastPingTime > 2000) //ping every 2 seconds?
                        {
                            inf.LastPingTime = nowMs;
                            var om = new NetDataWriter();
                            om.Put(LNetConst.PING_MAGIC);
                            client.SendUnconnectedMessage(om, inf.EndPoint);
                        }
                    }
                }
                //events
                client.PollEvents();
                Thread.Sleep(1);
            }
            client.DisconnectAll();
            client.Stop();
        }
Пример #5
0
        void NetworkThread()
        {
            sw = Stopwatch.StartNew();
            var conf = new NetPeerConfiguration(NetConstants.DEFAULT_APP_IDENT);

            conf.EnableMessageType(NetIncomingMessageType.UnconnectedData);
            conf.DualStack = true;
            client         = new NetClient(conf);
            client.Start();
            NetIncomingMessage im;

            while (running)
            {
                //ping servers
                lock (srvinfo)
                {
                    foreach (var inf in srvinfo)
                    {
                        var nowMs = (long)(NetTime.Now * 1000);
                        if (nowMs - inf.LastPingTime > 600)
                        {
                            inf.LastPingTime = nowMs;
                            var om = client.CreateMessage();
                            om.Write(NetConstants.PING_MAGIC);
                            client.SendUnconnectedMessage(om, inf.EndPoint);
                        }
                    }
                }
                while ((im = client.ReadMessage()) != null)
                {
                    try
                    {
                        switch (im.MessageType)
                        {
                        case NetIncomingMessageType.DebugMessage:
                        case NetIncomingMessageType.ErrorMessage:
                        case NetIncomingMessageType.WarningMessage:
                        case NetIncomingMessageType.VerboseDebugMessage:
                            FLLog.Info("Lidgren", im.ReadString());
                            break;

                        case NetIncomingMessageType.UnconnectedData:
                            lock (srvinfo)
                            {
                                foreach (var info in srvinfo)
                                {
                                    if (info.EndPoint.Equals(im.SenderEndPoint))
                                    {
                                        var t = (long)(im.ReceiveTime * 1000);
                                        info.Ping = (int)(t - info.LastPingTime);
                                        if (info.Ping < 0)
                                        {
                                            info.Ping = 0;
                                        }
                                    }
                                }
                            }
                            break;

                        case NetIncomingMessageType.DiscoveryResponse:
                            if (ServerFound != null)
                            {
                                var info = new LocalServerInfo();
                                info.EndPoint       = im.SenderEndPoint;
                                info.Name           = im.ReadString();
                                info.Description    = im.ReadString();
                                info.DataVersion    = im.ReadString();
                                info.CurrentPlayers = im.ReadInt32();
                                info.MaxPlayers     = im.ReadInt32();
                                info.LastPingTime   = sw.ElapsedMilliseconds;
                                var om = client.CreateMessage();
                                om.Write(NetConstants.PING_MAGIC);
                                client.SendUnconnectedMessage(om, info.EndPoint);
                                lock (srvinfo) srvinfo.Add(info);
                                mainThread.QueueUIThread(() => ServerFound?.Invoke(info));
                            }
                            break;

                        case NetIncomingMessageType.StatusChanged:
                            var status = (NetConnectionStatus)im.ReadByte();
                            if (status == NetConnectionStatus.Disconnected)
                            {
                                FLLog.Info("Net", "Disconnected");
                                var reason = im.ReadString();
                                mainThread.QueueUIThread(() => Disconnected?.Invoke(reason));
                                running = false;
                            }
                            break;

                        case NetIncomingMessageType.Data:
                            var pkt = im.ReadPacket();
                            if (connecting)
                            {
                                if (pkt is AuthenticationPacket)
                                {
                                    var auth = (AuthenticationPacket)pkt;
                                    FLLog.Info("Net", "Authentication Packet Received");
                                    if (auth.Type == AuthenticationKind.Token)
                                    {
                                        FLLog.Info("Net", "Token");
                                        var str = im.ReadString();
                                        mainThread.QueueUIThread(() => AuthenticationRequired(str));
                                    }
                                    else if (auth.Type == AuthenticationKind.GUID)
                                    {
                                        FLLog.Info("Net", "GUID");
                                        var response = client.CreateMessage();
                                        response.Write(new AuthenticationReplyPacket()
                                        {
                                            Guid = this.UUID
                                        });
                                        client.SendMessage(response, NetDeliveryMethod.ReliableOrdered);
                                    }
                                }
                                else if (pkt is LoginSuccessPacket)
                                {
                                    connecting = false;
                                }
                                else
                                {
                                    client.Disconnect("Invalid Packet");
                                }
                            }
                            else
                            {
                                packets.Enqueue(pkt);
                            }
                            break;
                        }
                    }
                    catch (Exception)
                    {
                        FLLog.Error("Net", "Error reading message of type " + im.MessageType.ToString());
                        throw;
                    }
                    client.Recycle(im);
                }
                Thread.Sleep(1);
            }
            FLLog.Info("Lidgren", "Client shutdown");
            client.Shutdown("Shutdown");
        }
Пример #6
0
 public void StartDiscovery(int port, ServerFound callback)
 {
     this.callback = callback;
     this.DiscoverLocalPeers(port);
 }