Exemplo n.º 1
0
    public void Terminate()
    {
        Utility.Log("NetThread terminated");

        if (!m_terminate)
        {
            m_terminate = true;
            if (null != m_loginClient)
            {
                m_loginClient.Close();
                m_loginClient = null;
            }
            if (null != m_gateClient)
            {
                m_gateClient.Close();
                m_gateClient = null;
            }
            if (null != m_crossClient)
            {
                m_crossClient.Close();
                m_crossClient = null;
            }
            m_thread.Join();
            m_thread = null;
        }
    }
        //-------------[ Close interfaces ]--------------------------//
        internal void Close(bool disableRelogin, bool waitConnectingCannelled)
        {
            bool isConnecting = false;

            lock (interLocker)
            {
                if (status == ClientStatus.Closed)
                {
                    return;
                }

                requireClose = true;

                if (disableRelogin && autoReloginInfo != null)
                {
                    autoReloginInfo.Disable();
                }

                if (status == ClientStatus.Connecting)
                {
                    isConnecting = true;
                }
                else
                {
                    status = ClientStatus.Closed;
                }
            }

            rtmGate.Close();

            if (isConnecting && waitConnectingCannelled)
            {
                syncConnectingEvent.WaitOne();
            }
        }
Exemplo n.º 3
0
    void OnGUI()
    {
        GUI.matrix = Matrix4x4.Scale(Vector3.one * 3);
        GUILayout.BeginArea(new Rect(10, 10, 200, 400));
        GUILayout.Label("TCP/IP CLIENT: " + connectStatus);

        client.m_serverIp = GUILayout.TextField(client.m_serverIp);
        client.m_port     = int.Parse(GUILayout.TextField(client.m_port.ToString()));
        if (GUILayout.Button("ConnectToServer"))
        {
            client.ConnectToServer();
        }
        if (GUILayout.Button("Close"))
        {
            client.Close();
        }

        GUILayout.Space(20);
        GUILayout.Label("RECEIVE: " + receiveStr);
        GUILayout.Space(20);
        sendStr = GUILayout.TextField(sendStr);
        if (GUILayout.Button("Send"))
        {
            client.Send(sendStr);
        }
        GUILayout.EndArea();
    }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            var host = "localhost";
            var port = 9999;

            Console.WriteLine($"This is an example TCP Client. Press any key to connect to tcp://{host}:{port}");
            var client = new TCPClient(host, port);

            client.OnMessage += OnReceive;
            client.Open();

            string input;

            while ((input = Console.ReadLine()).ToLower() != "quit")
            {
                if (input.ToLower() == "state")
                {
                    var state = new TransformState();
                    state.tick = simulatedTick++;
                    client.Send(Packet.Create(CommandEnum.StateUpdate, state.ToBytes()));
                }
                if (input.ToLower() == "deltastate")
                {
                    var deltaState = new TransformDeltaState();
                    deltaState.startStateTick = simulatedTick - 1;
                    deltaState.endStateTick   = simulatedTick++;
                    client.Send(Packet.Create(CommandEnum.DeltaStateUpdate, deltaState.ToBytes()));
                }
            }
            client.Close();
        }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("Usage: ConnectionEvents <ip> <port>");
                return;
            }

            TCPClient client = new TCPClient(args[0], Int32.Parse(args[1]));

            client.SetConnectionConnectedDelegate((Int64 connectionId, string endpoint, bool connected) => {
                if (connected)
                {
                    Console.WriteLine("Connected event triggered. Remote endpoint is {0}, connection id is {1}", endpoint, connectionId);
                }
                else
                {
                    Console.WriteLine("Connect {0} failed.", endpoint);
                }
            });

            client.SetConnectionCloseDelegate((Int64 connectionId, string endpoint, bool causedByError) => {
                Console.WriteLine("Connection {0} with {1} is closed by error {2}", connectionId, endpoint, causedByError);
            });

            if (client.SyncConnect())
            {
                Thread.Sleep(1000);
                client.Close();
                Thread.Sleep(1000);
            }
        }
Exemplo n.º 6
0
 private void OnDisable()
 {
     client.Close();
     client.OnOpen    -= InvokeOnOpen;
     client.OnMessage -= InvokeOnMessage;
     client.OnClose   -= InvokeOnClose;
     client.OnError   -= InvokeOnError;
 }
Exemplo n.º 7
0
 public void Disconnect()
 {
     TCPClient.Close();
     TCPClient     = null;
     Stream        = null;
     ReceiveBuffer = null;
     ReceivePacket = null;
 }
Exemplo n.º 8
0
 public void Dispose()
 {
     TCPClient.Close();
     TCPClient.Dispose();
     Writer.Close();
     Writer.Dispose();
     Reader.Close();
     Reader.Dispose();
 }
Exemplo n.º 9
0
 public void Close()
 {
     CancellationSource.Cancel();
     try
     {
         TCPClient.Close();
     }
     catch { }
 }
Exemplo n.º 10
0
 private void DisConnectClick()
 {
     if (is_connect)
     {
         TCPClient client = TCPClient.Instance;
         client.Close();
         server.Stop();
         is_connect = false;
     }
 }
Exemplo n.º 11
0
 public void Close()
 {
     if (Client != null)
     {
         Client.Close();
     }
     if (Server != null)
     {
         Server.Close();
     }
 }
Exemplo n.º 12
0
 /// <summary>
 /// 断开cdss服务
 /// </summary>
 private void CloseConnectToCdssServer()
 {
     try
     {
         ThreadControl = true;
         MyTcpClient.Close();
     }
     catch
     {
     }
 }
Exemplo n.º 13
0
        public void DownloadToClient(String server, string remotefilename, string localfilename)
        {
            try
            {
                TCPClient tcpc = new TCPClient();
                Byte[]    read = new Byte[1024];

                OptionsLoader ol   = new OptionsLoader();
                int           port = 0;
                if (ol.Port > 0)
                {
                    port = ol.Port;
                }
                else
                {
                    // The default in case nothing else is set
                    port = 8081;
                }


                // Try to connect to the server
                IPAddress  adr = new IPAddress(server);
                IPEndPoint ep  = new IPEndPoint(adr, port);
                if (tcpc.Connect(ep) == -1)
                {
                    throw new Exception("Unable to connect to " + server + " on port " + port);
                }

                // Get the stream
                Stream s = tcpc.GetStream();
                Byte[] b = Encoding.ASCII.GetBytes(remotefilename.ToCharArray());
                s.Write(b, 0, b.Length);
                int          bytes;
                FileStream   fs = new FileStream(localfilename, FileMode.OpenOrCreate);
                BinaryWriter w  = new BinaryWriter(fs);

                // Read the stream and convert it to ASII
                while ((bytes = s.Read(read, 0, read.Length)) != 0)
                {
                    w.Write(read, 0, bytes);
                    read = new Byte[1024];
                }

                tcpc.Close();
                w.Close();
                fs.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }
Exemplo n.º 14
0
 internal void Stop()
 {
     if (enabled)
     {
         xClient.Send(Encoding.ASCII.GetBytes("[" + Aura_OS.System.Time.TimeString(true, true, true) + "] - Properly disconnected by the operating system!"));
         xClient.Close();
         Uszka.Kernel.debugger.enabled = false;
     }
     else
     {
         Console.WriteLine("Debugger already disabled!");
     }
 }
Exemplo n.º 15
0
 public override void Stop()
 {
     // Stop listening for new clients.
     if (LinkStatus)
     {
         Console.WriteLine("Closing the TCP linking.");
         TCPClient.Close();
     }
     Console.WriteLine("Stopping the TCP linking service.");
     TCPService.Stop();
     Status     = false;
     LinkStatus = false;
 }
Exemplo n.º 16
0
 public override void Disconnect()
 {
     if (Status)
     {
         TCPClient.Close();
         Status = false; // setting the status to false
         Program.RegisterLinkedImplants();
     }
     else
     {
         Console.Error.WriteLine("The TCP link is not connected.");
     }
 }
Exemplo n.º 17
0
        private void AuthFinish(bool authStatus, int errorCode)
        {
            AuthStatusInfo currInfo;
            TCPClient      client       = null;
            long           connectionId = 0;
            long           currUid;

            lock (interLocker)
            {
                if (status != ClientStatus.Connecting)
                {
                    return;
                }

                if (authStatus)
                {
                    status = ClientStatus.Connected;
                    authStatsInfo.rtmClients.Remove(rtmGate);
                }
                else
                {
                    status              = ClientStatus.Closed;
                    connectionId        = rtmGateConnectionId;
                    rtmGateConnectionId = 0;
                    client              = rtmGate;
                    rtmGate             = null;
                }

                currInfo      = authStatsInfo;
                authStatsInfo = null;
                currUid       = uid;

                syncConnectingEvent.Set();
            }

            if (currInfo != null)
            {
                currInfo.authCallback(pid, currUid, authStatus, errorCode);
            }

            if (connectionId != 0)
            {
                RTMControlCenter.UnregisterSession(connectionId);
            }

            if (client != null)
            {
                client.Close();
            }
        }
Exemplo n.º 18
0
 /// <summary>
 /// Dispose
 /// </summary>
 public void Dispose()
 {
     if (TCPClient != null)
     {
         TCPClient.Close();
         TCPClient     = null;
         NetworkStream = null;
     }
     if (listenerThread != null)
     {
         listenerThread.Join();
         listenerThread = null;
     }
 }
Exemplo n.º 19
0
        static void Main(string[] args)
        {
            var host = "localhost";
            var port = 9999;

            Console.WriteLine($"This is an example TCP Client. Press any key to connect to tcp://{host}:{port}");
            Console.ReadKey();

            var client = new TCPClient(port);

            client.Open();
            Console.ReadKey();
            client.Close();
        }
Exemplo n.º 20
0
 public void Terminate()
 {
     if (!m_terminate)
     {
         m_terminate = true;
         if (null != m_loginClient)
         {
             m_loginClient.Close();
             m_loginClient = null;
         }
         if (null != m_gateClient)
         {
             m_gateClient.Close();
             m_gateClient = null;
         }
         if (null != m_crossClient)
         {
             m_crossClient.Close();
             m_crossClient = null;
         }
         m_thread.Join();
         m_thread = null;
     }
 }
        public void ProcessClose()
        {
            if (_timers != null)
            {
                _timers.Remove(-2);
            }

            _timers = null;

            if (_client.IsConnected())
            {
                _client.Close();
            }

            SetState(ConnectionState.NONE);
            return;
        }
Exemplo n.º 22
0
        public void DoubleConnectTest()
        {
            _tcp.DataReceived += DoubleConnectMethod;
            //_tcp.Open();
            var client1 = new TCPClient("127.0.0.1", 13000);

            //client1.Open();
            client1.Send("asdf1\n");
            Thread.Sleep(1000);
            client1.Close();
            Assert.AreEqual("asdf1\n", _msg);
            Thread.Sleep(1000);
            client1.Open();
            Thread.Sleep(1000);
            client1.Send("asdf2");
            Thread.Sleep(1000);
            Assert.AreEqual(_msg, "asdf2");
            //Thread.Sleep(10000);
        }
Exemplo n.º 23
0
        static void Main(string[] args)
        {
            //Console.OutputEncoding = Encoding.U;

            //Объвляем сокет-сервер (к нему будут подключаться клиенты)
            listener            = new TCPSListener("127.0.0.1", 1452);
            listener.onMessage += ReceiveMessage;
            listener.StartListen();

            Console.WriteLine("Запущен сокет-сервер по адресу " + listener.Adress);


            client            = new TCPClient("127.0.0.1", 1452);
            client.onMessage += ReceiveMessage;
            client.StartListen();

            client1            = new TCPClient("127.0.0.1", 1452);
            client1.onMessage += ReceiveMessage;
            client1.StartListen();

            Random rnd = new Random();

            while (true)
            {
                Console.ReadKey();
                client.Send("Первый клиент");
                client1.Send("Второй клиент");
                if (rnd.Next(0, 100) == 35)
                {
                    client.Close();
                }
                if (rnd.Next(0, 100) == 13)
                {
                    client1.Close();
                }
                if (rnd.Next(0, 100) == 13)
                {
                    listener.Close();
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        static void TcpDemo()
        {
            TCPListener listener = new TCPListener();
            TCPClient   client   = new TCPClient("127.0.0.1");

            listener.Start();

            client.Start();

            client.Send("Hello World");

            for (int i = 0; i < 100; i++)
            {
                client.Send(getRandomCoords());
            }

            Console.ReadKey();

            client.Close();
            listener.Close();
        }
Exemplo n.º 25
0
        void client_Received(TCPClient sender, byte[] data)
        {
            var memoryStream = new MemoryStream(data);
            var msg          = (NetworkPacket)(new BinaryFormatter()).Deserialize(memoryStream);

            switch (msg.Type)
            {
            case MessageType.InitialDetails:
                break;

            case MessageType.LoggedInElsewhere:                //handle DC request response
                if (msg.Result == CommunicationResult.Success) //This should allways be true, but check it anyways
                {
                    //Close connection
                    sender.Close();
                    _connections.Remove(sender);
                }
                break;

            case MessageType.WinampCommand:
                _eventAggregator.PublishOnUIThread(msg.WinampCommand);
                break;
            }
        }
Exemplo n.º 26
0
        private void ParallelConnectToRtmGate(string endpoint, ParallelLoginStatusInfo info)
        {
            if (!AdjustAuthRemainedTimeout(info))
            {
                DecreaseParallelConnectingCount();
                return;
            }

            TCPClient client = TCPClient.Create(endpoint, false);

            lock (interLocker)
            {
                if (status != ClientStatus.Connecting)
                {
                    return;
                }

                authStatsInfo.rtmClients.Add(client);
            }
            ConfigRtmGateClient(client, (Int64 connectionId, string rtmGateEndpoint, bool connected) => {
                if (requireClose)
                {
                    DecreaseParallelConnectingCount();
                    return;
                }

                if (connected)
                {
                    lock (interLocker)
                    {
                        if (status != ClientStatus.Connecting)
                        {
                            return;
                        }

                        authStatsInfo.parallelConnectingCount -= 1;
                        if (authStatsInfo.parallelCompleted)
                        {
                            return;
                        }

                        authStatsInfo.parallelCompleted       = true;
                        authStatsInfo.remainedTimeout         = info.remainedTimeout;
                        authStatsInfo.lastActionMsecTimeStamp = info.lastActionMsecTimeStamp;

                        rtmGate = client;
                    }

                    rtmGateConnectionId          = connectionId;
                    lastAvailableRtmGateEndpoint = endpoint;
                    RTMControlCenter.RegisterSession(rtmGateConnectionId, this);
                    Auth();
                }
                else
                {
                    DecreaseParallelConnectingCount();
                }
            }, info.remainedTimeout);
            client.AsyncConnect();

            if (requireClose)
            {
                client.Close();
            }
        }
Exemplo n.º 27
0
        private void TestWorker(object obj)
        {
            int qps  = (int)obj;
            int msec = 1000 / qps;

            lock (this)
            {
                Console.WriteLine("-- qps: " + qps + ", sleep milliseconds interval: " + msec);
            }

            TCPClient client = new TCPClient(ip, port);

            ProcessEncrypt(client);
            if (!client.SyncConnect())
            {
                lock (this)
                {
                    Console.WriteLine("Client sync connect remote server " + ip + ":" + port + " failed.");
                }
            }

            while (running)
            {
                Quest quest     = GenQuest();
                Int64 send_time = ClientEngine.GetCurrentMicroseconds();

                client.SendQuest(quest, (Answer answer, int errorCode) =>
                {
                    if (errorCode != ErrorCode.FPNN_EC_OK)
                    {
                        Interlocked.Add(ref recvErrorCount, 1);
                        if (errorCode == ErrorCode.FPNN_EC_CORE_TIMEOUT)
                        {
                            lock (this)
                                Console.WriteLine("Timeouted occurred when recving.");
                        }
                        else
                        {
                            lock (this)
                                Console.WriteLine("Error occurred when recving..");
                        }
                    }
                    else
                    {
                        Interlocked.Add(ref recvCount, 1);

                        Int64 recv_time = ClientEngine.GetCurrentMicroseconds();
                        Int64 diff      = recv_time - send_time;
                        Interlocked.Add(ref timeCost, diff);
                    }
                });

                Interlocked.Add(ref sendCount, 1);

                Int64 sent_time = ClientEngine.GetCurrentMicroseconds();
                Int64 real_usec = msec * 1000 - (sent_time - send_time);
                if (real_usec > 1000)
                {
                    Thread.Sleep((int)(real_usec / 1000));
                }
                else if (real_usec > 500)
                {
                    Thread.Sleep(1);
                }
            }

            client.Close();
        }
Exemplo n.º 28
0
        public void DownloadToClient(String server, string remotefilename, string localfilename)
        {
            try
            {
                TCPClient tcpc = new TCPClient();
                Byte[] read = new Byte[1024];

                OptionsLoader ol = new OptionsLoader();
                int port = 0;
                if (ol.Port > 0)
                {
                    port = ol.Port;
                }
                else
                {
                    // The default in case nothing else is set
                    port = 8081;
                }

                // Try to connect to the server
                IPAddress adr = new IPAddress(server);
                IPEndPoint ep = new IPEndPoint(adr, port);
                if (tcpc.Connect(ep) == -1)
                {
                    throw new Exception("Unable to connect to " + server + " on port " + port);
                }

                // Get the stream
                Stream s = tcpc.GetStream();
                Byte[] b = Encoding.ASCII.GetBytes(remotefilename.ToCharArray());
                s.Write( b, 0,  b.Length );
                int bytes;
                FileStream fs = new FileStream(localfilename, FileMode.OpenOrCreate);
                BinaryWriter w = new BinaryWriter(fs);

                // Read the stream and convert it to ASII
                while( (bytes = s.Read(read, 0, read.Length)) != 0)
                {
                    w.Write(read, 0, bytes);
                    read = new Byte[1024];
                }

                tcpc.Close();
                w.Close();
                fs.Close();
            }
            catch(Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }
Exemplo n.º 29
0
 private void Client_onDisconnect()
 {
     parentDispatcher.UpdateServerList(this);
     client.Close();
 }
Exemplo n.º 30
0
 void OnDestroy()
 {
     _tcpClient.Close();
 }
Exemplo n.º 31
0
        private void DispatchCallBack_Which_IPv4(Answer answer, int errorCode)
        {
            if (requireClose)
            {
                AuthFinish(false, fpnn.ErrorCode.FPNN_EC_CORE_CONNECTION_CLOSED);
                return;
            }

            if (errorCode == fpnn.ErrorCode.FPNN_EC_OK)
            {
                if (!AdjustAuthRemainedTimeout())
                {
                    return;
                }

                string ipv4endpoint = answer.Get <string>("endpoint", string.Empty);
                if (ipv4endpoint.Length > 0)
                {
                    TCPClient client = TCPClient.Create(ipv4endpoint, false);
                    lock (interLocker)
                    {
                        rtmGate = client;
                        authStatsInfo.rtmClients.Add(client);
                    }
                    ConfigRtmGateClient(client, (Int64 connectionId, string endpoint, bool connected) => {
                        if (requireClose)
                        {
                            AuthFinish(false, fpnn.ErrorCode.FPNN_EC_CORE_CONNECTION_CLOSED);
                            return;
                        }

                        if (connected)
                        {
                            rtmGateConnectionId          = connectionId;
                            lastAvailableRtmGateEndpoint = ipv4endpoint;
                            RTMControlCenter.RegisterSession(rtmGateConnectionId, this);
                            Auth();
                        }
                        else
                        {
                            if (!AdjustAuthRemainedTimeout())
                            {
                                return;
                            }

                            StartParallelConnect(ipv4endpoint);
                        }
                    }, authStatsInfo.remainedTimeout);
                    client.AsyncConnect();

                    if (requireClose)
                    {
                        client.Close();
                    }
                    return;
                }
                else
                {
                    StartParallelConnect(string.Empty);
                }
            }
            else
            {
                AuthFinish(false, errorCode);
            }
        }