示例#1
0
        public void Close()
        {
            lock (SendLock)
            {
                if (listener != null)
                {
                    try
                    {
                        listener.Shutdown(SocketShutdown.Both);
                    }
                    finally
                    {
                        listener.Close();
                        listener = null;
                    }
                }

                StopThread();

                SocketList.Clear();
                Packets.Clear();
                ToPeer.Clear();
                SocketToKey.Clear();
                clientcheck.Clear();
                OnListenClient.Clear();

                GetMessage = null;

                RSAkey = new EncryptAndCompress.RSAKeyPair();
            }
        }
示例#2
0
        public void Disconnect(int timeout)
        {
            if (socket != null)
            {
                try
                {
                    socket.Shutdown(SocketShutdown.Both);
                }
                catch (Exception) { }
                finally
                {
                    if (timeout == -1)
                    {
                        socket.Close();
                    }
                    else
                    {
                        socket.Close(timeout);
                    }
                    socket = null;
                }
            }

            GetMessage = null;

            Packets.Clear();
            AESkey = null;
            RSAkey = new EncryptAndCompress.RSAKeyPair();
        }
示例#3
0
        public void Close()
        {
            if (listener != null)
            {
                try
                {
                    listener.Shutdown(SocketShutdown.Both);
                }
                catch (Exception) { }
                finally
                {
                    listener.Close();
                    listener = null;
                }
            }

            SocketList.Clear();
            Packets.Clear();
            ToPeer.Clear();
            SocketToEndPoint.Clear();
            SocketToKey.Clear();

            GetMessage = null;

            RSAkey = new EncryptAndCompress.RSAKeyPair();
        }
示例#4
0
 public void BuildPackets()
 {
     Packets.Clear();
     if (_data.Count > 1)
     {
         Packets.AddRange(Tools.Builder.GetPackets(_data, Options));
         PacketsBuilt?.Invoke(this, new PacketsBuiltEventArgs(Packets));
     }
 }
        private void StartCaptureCmdExecute()
        {
            if (packetReceiveThread != null)
            {
                packetReceiveThread.Abort();
                packetReceiveThread = null;
            }

            Packets.Clear();
            packetReceiveThread          = new Thread(new ThreadStart(PacketHandler));
            packetReceiveThread.Priority = ThreadPriority.AboveNormal;
            packetReceiveThread.Start();
            StatHandler.Start();
        }
示例#6
0
        private void Refresh()
        {
            //var output = new StringBuilder();
            Packets.Clear();

            //Create the reader
            using (var captureReader = new CaptureFileReader(_captureFilePath))
            {
                var sample = captureReader.Read();

                //Keep track of the last sample so we now how far apart they are
                Sample lastSample = null;

                var buffer = new List <byte>();

                var captureTimerInfo = new CaptureTimerInfo(captureReader.StartTime, captureReader.TicksPerSecond);

                while (sample != null)
                {
                    if (lastSample != null)
                    {
                        //Get the elapsed Ms
                        var elapsedMs = captureTimerInfo.TicksToMilliseconds(sample.Ticks - lastSample.Ticks);

                        if (elapsedMs >= _packetThreshold)
                        {
                            Packets.Add(new PacketViewModel(buffer.ToArray()));
                            buffer.Clear();
                        }
                    }

                    //Add an item to the buffer
                    buffer.Add(sample.Value);

                    //Save this sample for next time
                    lastSample = sample;

                    //Get the next sample
                    sample = captureReader.Read();

                    //See if we have any last bits... (might take this out)
                    if (sample == null && buffer.Any())
                    {
                        Packets.Add(new PacketViewModel(buffer.ToArray()));
                        buffer.Clear();
                    }
                }
            }
        }
示例#7
0
        public void Dispose()
        {
            // n.b. Resize uses this -- we may need to refactor if we need to do something permanent

            LoadCancel = true;
            LoadThread.Join();
            foreach (var ap in Packets)
            {
                using (ap.RestartPosition) {}
            }
            Packets.Clear();

            Debug.Assert(!LoadThread.IsAlive);    // We assert this...
            LoadPacketBuffer.Clear();             // ... because we're not locking this.
        }
示例#8
0
 public override bool Init(IPAddress server, ushort port, List <byte> data)
 {
     Socket.Close();
     Packets.Clear();
     try
     {
         Logger.Write("Connecting to {0}:{1}", server, port);
         Socket = new System.Net.Sockets.TcpClient();
         Socket.Connect(server, port);
         Stream = Socket.GetStream();
         Logger.Write(" Connected");
     }
     catch
     {
         Logger.Write(" Failed To connect");
         return(false);
     }
     OnStartThread();
     return(true);
 }
示例#9
0
        public void BuildMessage(HeaderType messageType, byte[] lPayLoad)
        {
            var packet_size = 4096 - 8;

            Packets.Clear();

            for (var lower = 0; lower < lPayLoad.Length; lower += packet_size)
            {
                var payloadSize = lPayLoad.Length - lower;
                if (payloadSize > packet_size)
                {
                    payloadSize = packet_size;
                }

                // Create new TDS header
                var header = new TDSHeader();
                header.Type = messageType;
                if (lPayLoad.Length - lower <= packet_size)
                {
                    header.StatusBitMask = StatusBitMask.END_OF_MESSAGE;
                }
                else
                {
                    header.StatusBitMask = StatusBitMask.NORMAL;
                }
                header.PayloadSize = payloadSize;

                var payload = new byte[payloadSize];
                Array.Copy(lPayLoad, lower, payload, 0, payloadSize);

                // Create new TDS packet with new TDS header and payload
                var newPacket = new TDSPacket(header.Data, payload, payloadSize);

                // Add packet into message
                Packets.Add(newPacket);
            }
        }
示例#10
0
    void FirstContact()
    {
        string Mex;



        //Primo Contatto
        Pacchetto.Destinatario = Servente;
        Pacchetto.Clear();


        try
        {
            Mex = Pacchetto.First_Contact(1, false).ToString();
            Pacchetto.Send_Packet("Client", "Errore durante invio first Contact");

            Pacchetto.Clear();
            Pacchetto.Receive_Packet("Client", 1);
            if (Pacchetto.Get_Header())
            {
                if (Pacchetto.Header == 0)
                {
                    Mex = Pacchetto.First_Contact(0, true).ToString();
                    switch (Mex)
                    {
                    case "3":
                        settings.Console_Write("Il server ha rifiutato la tua connessione causa codice", false);
                        Shutdown_Client("Client => FirstContact (ByServerRefuse)");
                        return;

                    case "4":
                        settings.Console_Write("Benvenuto", false);
                        break;

                    default:
                        settings.Error_Profiler("N015", 0, "(Client)Codice First contact errato", 3, false);
                        Shutdown_Client("Client => FirstContact (ByWrongBodyCode)");
                        return;
                    }
                }
            }
            else
            {
                settings.Error_Profiler("N014", 0, "(Client)Errore nel Header:" + Name + " > Test di invio", 3, false);
                Shutdown_Client("Client => FirstContact (ByError)");
            }
            if (!Pacchetto.Risultato)
            {
                settings.Error_Profiler("N011", 0, "(Client)Errore nell'invio del pacchetto:" + Name + " > Test di invio", 3, false);
                Shutdown_Client("Client => FirstContact (ByError)");
            }
        }
        catch (Exception e)
        {
            if (Shutdown)
            {
                if (D)
                {
                    settings.Console_Write("Client non più in comunicazione (Inizialize_Client)", false);
                }
            }
            else
            {
                settings.Error_Profiler("N010", 0, "Errore nell'inizializzazione\n" + e, 2, false);
                Shutdown_Client("Client => FirstContact");
            }
        }



        return;


        //OLD

        try
        {
            Pacchetto.Set_Header(1, "Errore durante il primo contatto");
            Mex = "";

            Mex = Send.Receive_by_one(Servente, 1, Name);

            settings.Console_Write("Messaggio ricevuto dal client: " + Mex, false);

            Shutdown_Client("Fine comunicazione");

            if (Int32.Parse(Mex) == 0)
            {
                Debug.LogError("Ti è stato negato l'accesso al server causa Nome o motivazione");
                Shutdown_Client("Client => FirstContact");
            }
        }
        catch (Exception e)
        {
            if (Shutdown)
            {
                if (D)
                {
                    settings.Console_Write("Client non più in comunicazione (Username)", false);
                }
            }
            else
            {
                settings.Error_Profiler("N010", 0, "Errore nel passaggio dell'username\n" + e, 2, false);
                Shutdown_Client("Client => FirstContact");
            }
        }

        if (!Shutdown)
        {
            //richiesta di aggiornamento lobby
            try
            {
                List <int> IDlist     = gameObject.GetComponent <Lobby>().List_of_ID();
                List <int> OnlineList = new List <int>();
                for (int I = 0; I < IDlist.Count; I++)
                {
                    OnlineList.Add(gameObject.GetComponent <Lobby>().Check_Online_by_ID(IDlist[I]));
                }
                Send.Send_to_One(Name, Send.Refresh_Lobby(IDlist, OnlineList), Servente, "Errore durante la richiesta di refresh della lobby");
            }
            catch (Exception e)
            {
                if (Shutdown)
                {
                    if (D)
                    {
                        settings.Console_Write("Client non più in comunicazione (Aggiornamento Lobby)", false);
                    }
                }
                else
                {
                    settings.Error_Profiler("D001", 0, "Errore nella richiesta di aggiornamento della lobby \n" + e, 2, false);
                    Shutdown_Client("Client => FirstContact");
                }
            }
        }
    }
示例#11
0
    public void SubThr(object TempSocket)
    {
        Actions     action = new Actions();
        SendActions Send   = new SendActions();

        action.AsServer = true;
        action.Send     = Send;
        action.lobby    = lobby;
        Send.lobby      = lobby;
        Socket client = (Socket)TempSocket;

        SocketList.Add(client);

        string     Name     = null;                                         //
        string     Mex      = null;                                         //
        IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;            //IP del client

        client.NoDelay           = true;                                    //imposto che invia sempre in base alla dimensione che riceve senza dover riempire il pacchetto
        client.ReceiveBufferSize = action.BufferSize;                       //imposto la dimensione massima del buffersize per action
        action.lobby             = lobby;
        Send.BufferSize          = action.BufferSize;                       //Imposto la dimesione massima del buffersize per Send
        Send.lobby = lobby;

        Packets Pacchetto = new Packets();

        Pacchetto.Inizialize_Packet(D, true, settings, lobby, "Server ==> (" + clientep.ToString() + ")");


        if (D)
        {
            settings.Console_Write("Connesso con: " + clientep, false);
        }



        // Primo contatto
        try
        {
            Pacchetto.Destinatario = client;
            Pacchetto.Clear();



            Pacchetto.Receive_Packet("Server", 1);
            Pacchetto.Get_Header();
            if (Pacchetto.Header == 0 && Pacchetto.Risultato)
            {
                int T = Pacchetto.Fetch_Header(Pacchetto.Header);
                Pacchetto.Receive_Packet("Server", T);
                if (!Pacchetto.Risultato)
                {
                    settings.Console_Write("Server > Errore di comunicazione (FIrstCOntact).", false);
                }
                T   = Pacchetto.First_Contact(255, true);
                Mex = T.ToString();
            }
            else
            {
                settings.Console_Write("Server > Errore di comunicazione (FIrstCOntact). pt2", false);
            }
            Pacchetto.Clear();
            //Mex =  Send.Receive_by_one(client, 1, "Server");
            switch (Mex)
            {
            case "1":
                settings.Console_Write("Server > Client connesso come giocatore. " + Mex, false);
                Pacchetto.First_Contact(4, false);
                Pacchetto.Send_Packet("Server", "Errore durante la risposta al FirstCOntact per vero");
                break;

            case "2":
                settings.Console_Write("Server > Client connesso per invio dati. " + Mex, false);
                Pacchetto.First_Contact(5, false);
                Pacchetto.Send_Packet("Server", "Errore durante la risposta al FirstCOntact per falso");
                break;

            default:
                settings.Error_Profiler("N014", 0, "Codice header non consono. Codice ricevuto:" + Mex, 2, false);
                Pacchetto.First_Contact(5, false);
                Pacchetto.Send_Packet("Server", "Errore durante la risposta al FirstCOntact per falso");
                break;
            }
            Close_Single_ConnectedClient(client);
            return;
        }
        catch (Exception e)
        {
            if (Shutdown)
            {
                if (D)
                {
                    settings.Console_Write("connessione con " + Name + "  (" + clientep.ToString() + ") chiusa.", false);
                }
            }
            else
            {
                settings.Error_Profiler("N012", 0, "(" + Name + " || " + clientep.ToString() + ") (Server => SubThr) : " + e, 1, false);
                Send.Server_Broadcast(Send.Player_Come_Online(lobby.Retrive_ID_by_Name(Name), false));
                lobby.Set_Online_by_ID(lobby.Retrive_ID_by_Name(Name), false);
                Close_Single_ConnectedClient(client);
            }
        }



        // fine primo contatto


        if (!Shutdown)
        {
            try
            {
                if (D == true)
                {
                    settings.Console_Write("Connesso con: " + clientep, false);
                }

                //richiedo il motivo di connessione e nel caso l'username
                string[] ConnetionMotivation = Send.Receive_by_one(client, 1, "Server").Split('#');
                switch (Int32.Parse(ConnetionMotivation[0]))          //controllo se si connette per inviare immagini
                {
                case 0:
                    break;

                case 1:
                    TransferChannel();
                    return;

                default:
                    Send.Send_to_One("Server", "0", client, "Errore nella della motivazione di connessione");
                    return;
                }



                Name = ConnetionMotivation[1];
                if (!lobby.Check_Exist_by_Name(Name))
                {
                    lobby.Add_ServerPlayer(client, Name, 0);
                }
                else
                {
                    if (lobby.Check_Online_by_ID(lobby.Retrive_ID_by_Name(Name)) != 0)
                    {
                        Debug.LogError("Esiste già un client connesso con il nome: " + Name + " chiusura connessione");

                        Send.Send_to_One("Server", "0", client, "Errore nella comunicazione dell'errato nome");
                        client.Close();
                        return;
                    }
                    else
                    {
                        lobby.Set_Online_by_ID(lobby.Retrive_ID_by_Name(Name), true);
                        lobby.Set_User_by_ID(lobby.Retrive_ID_by_Name(Name), client);
                        Send.Server_Broadcast(Send.Player_Come_Online(lobby.Retrive_ID_by_Name(Name), true));
                    }
                }


                //avverto che l'username è stato accettato
                Send.Send_to_One("Server", "1", client, "Errore nella comunicazione della genuinità del nome");

                //aggiorno tutti sul nuovo host connesso
                Send.Server_Broadcast(Send.Client_Player_Login_Inizialize(lobby.Retrive_ID_by_Name(Name), 0, 1, Name));
                while (true)
                {
                    Mex = Send.Receive_by_one(client, 1, "Server");

                    if (D)
                    {
                        Debug.Log("S_Ricevuto: " + Mex);
                    }
                    Actions TempActions = new Actions
                    {
                        User     = client,
                        Ricevuto = Mex,
                        contesto = 0,
                        lobby    = lobby,
                        AsServer = true,
                    };
                    Thread newThread = new Thread(new ParameterizedThreadStart(TempActions.Run));
                    newThread.Start(client);
                }
                if (D == true)
                {
                    Debug.Log("il Client si è disconnesso");
                }
                lobby.Set_Online_by_ID(lobby.Retrive_ID_by_Name(Name), false);
                client.Close();
            }
            catch (Exception e)
            {
                Debug.LogError("Il socket " + clientep + " si è disconnesso a causa di un errore\n" + e);
                Send.Server_Broadcast(Send.Player_Come_Online(lobby.Retrive_ID_by_Name(Name), false));
                lobby.Set_Online_by_ID(lobby.Retrive_ID_by_Name(Name), false);
                client.Close();
                return;
            }
        }
    }
示例#12
0
        public override void Tick()
        {
            if (tdisco)
            {
                return;
            }
            if (!IsValid)
            {
                return;
            }
            int pc = PacketsToApply.Count;

            for (int i = 0; i < pc; i++)
            {
                PacketsToApply[i].Apply();
            }
            PacketsToApply.RemoveRange(0, pc);
            TickMovement(InWorld.Delta);
            // Manage Selection
            Location forward = Utilities.ForwardVector_Deg(Direction.X, Direction.Y);
            Location eye     = Position + new Location(0, 0, Maxes.Z);
            Location seltarg = eye + forward * 10;

            SelectedBlock = Collision.BoxRayTrace(InWorld, new Location(-0.001), new Location(0.001), eye, seltarg, -1);
            if (SelectedBlock == seltarg)
            {
                SelectedBlock = Location.NaN;
            }
            // Break
            if (Attack && !SelectedBlock.IsNaN())
            {
                if (ServerMain.GlobalTickTime - 0.5 >= LastBreak)
                {
                    LastBreak = ServerMain.GlobalTickTime;
                    Location sel_block = SelectedBlock.GetBlockLocation();
                    Chunk    ch        = InWorld.LoadChunk(World.GetChunkLocation(sel_block));
                    if (ch.Blocks[(int)(sel_block.X - ch.X * 30), (int)(sel_block.Y - ch.Y * 30), (int)(sel_block.Z - ch.Z * 30)].Type != 0)
                    {
                        ch.SetBlock((int)(sel_block.X - ch.X * 30), (int)(sel_block.Y - ch.Y * 30), (int)(sel_block.Z - ch.Z * 30), (ushort)Material.AIR);
                        InWorld.BroadcastBlock(sel_block);
                    }
                }
            }
            if (!Attack)
            {
                LastBreak = 0;
            }
            // Place
            Item HeldItem = GetItemForSlot(QuickBarPos);

            if (Secondary && HeldItem.Material != Material.AIR)
            {
                if (ServerMain.GlobalTickTime - 0.3 >= LastPlace)
                {
                    Location back_a_block = Collision.BoxRayTrace(InWorld, new Location(-0.001), new Location(0.001), eye, seltarg, 1);
                    LastPlace = ServerMain.GlobalTickTime;
                    Location sel_block = back_a_block.GetBlockLocation();
                    Chunk    ch        = InWorld.LoadChunk(World.GetChunkLocation(sel_block));
                    if (ch.Blocks[(int)(sel_block.X - ch.X * 30), (int)(sel_block.Y - ch.Y * 30), (int)(sel_block.Z - ch.Z * 30)].Type != (ushort)HeldItem.Material)
                    {
                        ch.SetBlock((int)(sel_block.X - ch.X * 30), (int)(sel_block.Y - ch.Y * 30), (int)(sel_block.Z - ch.Z * 30), (ushort)HeldItem.Material);
                        InWorld.BroadcastBlock(sel_block);
                    }
                }
            }
            if (!Secondary)
            {
                LastPlace = 0;
            }
            // TODO: Better tracking of what chunks to send
            List <Location> locs = GetChunksNear(World.GetChunkLocation(Position));

            foreach (Location loc in locs)
            {
                if (!ChunksAware.Contains(loc))
                {
                    ToSend.Add(loc);
                    ChunksAware.Add(loc);
                }
            }
            for (int i = 0; i < ChunksAware.Count; i++)
            {
                if (!locs.Contains(ChunksAware[i]))
                {
                    ToSend.Remove(ChunksAware[i]);
                    ChunksAware.RemoveAt(i--);
                }
            }
            sendtimer += InWorld.Delta;
            if (sendtimer >= 0.05f)
            {
                sendtimer = 0.05f;
                if (ToSend.Count > 0)
                {
                    Chunk ch = InWorld.LoadChunk(ToSend[0]);
                    SendToSecondary(new ChunkPacketOut(ch));
                    for (int i = 0; i < ch.Entities.Count; i++)
                    {
                        if (ch.Entities[i] != this)
                        {
                            Send(new NewEntityPacketOut(ch.Entities[i]));
                        }
                    }
                    ToSend.RemoveAt(0);
                }
            }
            // Handle networking
            lock (Packets)
            {
                for (int i = 0; i < Packets.Count; i++)
                {
                    try
                    {
                        Packets[i].Apply();
                    }
                    catch (Exception ex)
                    {
                        SysConsole.Output(OutputType.ERROR, "Networking / player / receive "
                                          + (Packets[i].IsChunkConnection ? "C-" : "") + "packet: " + ex.ToString());
                        Kick("Invalid packet " + Packets[i].GetType().Name); // TODO: Less internal-ish packet ID handling?
                    }
                }
                Packets.Clear();
            }
        }
示例#13
0
 private void Clear()
 {
     Packets.Clear();
     FilteredPackets.Clear();
 }
示例#14
0
文件: SpyHelper.cs 项目: deccer/SpyUO
 /// <summary>
 /// Clears packets.
 /// </summary>
 public void ClearPackets()
 {
     Count = 0;
     Packets.Clear();
 }