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(); } }
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(); }
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(); }
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); } }
private void OnDisable() { client.Close(); client.OnOpen -= InvokeOnOpen; client.OnMessage -= InvokeOnMessage; client.OnClose -= InvokeOnClose; client.OnError -= InvokeOnError; }
public void Disconnect() { TCPClient.Close(); TCPClient = null; Stream = null; ReceiveBuffer = null; ReceivePacket = null; }
public void Dispose() { TCPClient.Close(); TCPClient.Dispose(); Writer.Close(); Writer.Dispose(); Reader.Close(); Reader.Dispose(); }
public void Close() { CancellationSource.Cancel(); try { TCPClient.Close(); } catch { } }
private void DisConnectClick() { if (is_connect) { TCPClient client = TCPClient.Instance; client.Close(); server.Stop(); is_connect = false; } }
public void Close() { if (Client != null) { Client.Close(); } if (Server != null) { Server.Close(); } }
/// <summary> /// 断开cdss服务 /// </summary> private void CloseConnectToCdssServer() { try { ThreadControl = true; MyTcpClient.Close(); } catch { } }
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()); } }
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!"); } }
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; }
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."); } }
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(); } }
/// <summary> /// Dispose /// </summary> public void Dispose() { if (TCPClient != null) { TCPClient.Close(); TCPClient = null; NetworkStream = null; } if (listenerThread != null) { listenerThread.Join(); listenerThread = null; } }
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(); }
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; }
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); }
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(); }
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; } }
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(); } }
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(); }
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()); } }
private void Client_onDisconnect() { parentDispatcher.UpdateServerList(this); client.Close(); }
void OnDestroy() { _tcpClient.Close(); }
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); } }