コード例 #1
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();
        }
コード例 #2
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");
        }
コード例 #3
0
ファイル: LuaMenu.cs プロジェクト: lyzardiar/Librelancer
 void Client_ServerFound(LocalServerInfo obj)
 {
     serverList.Servers.Add(obj);
 }
コード例 #4
0
ファイル: MainMenu.cs プロジェクト: darkzter/Librelancer
 void ServerList_Selected(LibreLancer.LocalServerInfo obj)
 {
     selectedInfo = obj;
     serverDescription.Description = obj.Description;
     connectButton.Tag             = "srvlst_connect";
 }
コード例 #5
0
ファイル: GameClient.cs プロジェクト: TRBlount/Librelancer
        void NetworkThread()
        {
            var conf = new NetPeerConfiguration(NetConstants.DEFAULT_APP_IDENT);

            client = new NetClient(conf);
            client.Start();
            NetIncomingMessage im;

            while (running)
            {
                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.DiscoveryResponse:
                        if (ServerFound != null)
                        {
                            var info = new LocalServerInfo();
                            info.EndPoint       = im.SenderEndPoint;
                            info.Name           = im.ReadString();
                            info.Description    = im.ReadString();
                            info.CurrentPlayers = im.ReadInt32();
                            info.MaxPlayers     = im.ReadInt32();
                            mainThread.QueueUIThread(() => ServerFound(info));
                        }
                        break;

                    case NetIncomingMessageType.StatusChanged:
                        var status = (NetConnectionStatus)im.ReadByte();
                        if (status == NetConnectionStatus.Disconnected)
                        {
                            connecting = false;
                            Disconnected(im.ReadString());
                        }
                        break;

                    case NetIncomingMessageType.Data:
                        var kind = (PacketKind)im.ReadByte();
                        if (connecting)
                        {
                            if (kind == PacketKind.Authentication)
                            {
                                FLLog.Info("Net", "Authentication Packet Received");
                                var authkind = (AuthenticationKind)im.ReadByte();
                                if (authkind == AuthenticationKind.Token)
                                {
                                    FLLog.Info("Net", "Token");
                                    AuthenticationRequired(im.ReadString());
                                }
                                else if (authkind == AuthenticationKind.GUID)
                                {
                                    FLLog.Info("Net", "GUID");
                                    var response = client.CreateMessage();
                                    response.Write((byte)PacketKind.Authentication);
                                    response.Write((byte)AuthenticationKind.GUID);
                                    var arr = UUID.ToByteArray();
                                    foreach (var b in arr)
                                    {
                                        response.Write(b);
                                    }
                                    client.SendMessage(response, NetDeliveryMethod.ReliableOrdered);
                                }
                                else
                                {
                                    client.Shutdown("Invalid Packet");
                                }
                            }
                            else if (kind == PacketKind.AuthenticationSuccess)
                            {
                                connecting = false;
                                var inf = new CharacterSelectInfo();
                                inf.ServerNews = im.ReadString();
                                mainThread.QueueUIThread(() => CharacterSelection(inf));
                            }
                            else
                            {
                                client.Shutdown("Invalid Packet");
                            }
                            break;
                        }
                        switch (kind)
                        {
                        case PacketKind.NewCharacter:
                            if (im.ReadByte() == 1)
                            {
                                var credits = im.ReadInt32();
                                OpenNewCharacter(credits);
                            }
                            break;
                        }
                        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
 void ServerList_Selected(LibreLancer.LocalServerInfo obj)
 {
     selectedInfo = obj;
     serverDescription.Description = obj.Description;
     connectButton.Action          = ServerListConnect;
 }