public void BittimiKontrol(SimpleTCP.Message e) { if (e.MessageString.Contains("Kazandı")) { button1.Invoke((MethodInvoker) delegate() { button1.Text = ""; }); button2.Invoke((MethodInvoker) delegate() { button2.Text = ""; }); button3.Invoke((MethodInvoker) delegate() { button3.Text = ""; }); button4.Invoke((MethodInvoker) delegate() { button4.Text = ""; }); button5.Invoke((MethodInvoker) delegate() { button5.Text = ""; }); button6.Invoke((MethodInvoker) delegate() { button6.Text = ""; }); button7.Invoke((MethodInvoker) delegate() { button7.Text = ""; }); button8.Invoke((MethodInvoker) delegate() { button8.Text = ""; }); button9.Invoke((MethodInvoker) delegate() { button9.Text = ""; }); client.Disconnect(); baglan_button.Invoke((MethodInvoker) delegate(){ baglan_button.Enabled = true; }); } else { SiraKimde(e); } }
/// <summary> /// On button Connect / Disconnect to the server /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button_ConnectDisconnect_Click(object sender, EventArgs e) { string err; bool bError = true; string s = "Unknown error"; if (!bConnected) { // try to connect if (client.Connect(textBox_ServerIP.Text, (int)numericUpDown_Port.Value, out err)) { s = "Successfuly connected to the server"; bConnected = true; bError = false; } else { s = "Failed to connect to server: " + err; } } else { // always disconnect on error (the client object will be disconnected anyways after calling Disconnect() bConnected = false; // try to disconnect if (client.Disconnect(out err)) { s = "Successfuly disconnected from the server"; bError = false; } else { s = "Failed to disconnect from server: " + err; } } if (bError) { MessageBox.Show(s, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); } textBox_Receive.Text += "DEBUG > " + s + "\r\n"; textBox_Receive.SelectionStart = textBox_Receive.TextLength; textBox_Receive.ScrollToCaret(); button_ConnectDisconnect.Text = bConnected ? "DISCONNECT" : "CONNECT"; SetGUIstate(bConnected); }
private void Client_DataReceived(object sender, SimpleTCP.Message e) { string response = e.MessageString; if (response.Substring(0, 2) == "B3") { if (response.Substring(5, 7).Contains("TD")) { Application.OpenForms["HOME"].Controls.OfType <Label>().First(x => x.Name == "lblCurrent1").Text = response.Substring(5, 9); Application.OpenForms["HOME"].Controls.OfType <Label>().First(x => x.Name == "lblCurrent2").Text = response.Substring(15, 9); Application.OpenForms["HOME"].Controls.OfType <Label>().First(x => x.Name == "lblCurrent3").Text = response.Substring(25, 9); Application.OpenForms["HOME"].Controls.OfType <Label>().First(x => x.Name == "lblCurrent4").Text = response.Substring(35, 9); } else { Application.OpenForms["HOME"].Controls.OfType <Label>().First(x => x.Name == "lblCurrent1").Text = response.Substring(5, 7); Application.OpenForms["HOME"].Controls.OfType <Label>().First(x => x.Name == "lblCurrent2").Text = response.Substring(13, 7); Application.OpenForms["HOME"].Controls.OfType <Label>().First(x => x.Name == "lblCurrent3").Text = response.Substring(21, 7); Application.OpenForms["HOME"].Controls.OfType <Label>().First(x => x.Name == "lblCurrent4").Text = response.Substring(29, 7); } } else if (response.Substring(0, 2) == "RE") { if (response.Substring(3, 1) == "0") { if (response.Substring(5, 1) == "0") { Application.OpenForms["HOME"].Controls.OfType <Label>().First(x => x.Name == "lblReady").Text = "READY ON"; Application.OpenForms["HOME"].Controls.OfType <Label>().First(x => x.Name == "lblReady").ForeColor = System.Drawing.Color.FromArgb(0, 255, 0); } else if (response.Substring(5, 1) == "1") { Application.OpenForms["HOME"].Controls.OfType <Label>().First(x => x.Name == "lblReady").Text = "READY OFF"; Application.OpenForms["HOME"].Controls.OfType <Label>().First(x => x.Name == "lblReady").ForeColor = System.Drawing.Color.FromArgb(255, 0, 0); } else if (response.Substring(5, 1) == "2") { Application.OpenForms["HOME"].Controls.OfType <Label>().First(x => x.Name == "lblReady").Text = "READY OFF"; Application.OpenForms["HOME"].Controls.OfType <Label>().First(x => x.Name == "lblReady").ForeColor = System.Drawing.Color.FromArgb(255, 0, 0); } } else { MessageBox.Show("An error has ocurred. Please Restart", "Error Status"); client.Disconnect(); Application.OpenForms["HOME"].Close(); } } }
public void Dispose() { _socket.Disconnect(); _socket.Close(); _socket = null; if (_sender != null) { _sender.Disconnect(); _sender.Dispose(); _sender = null; } if (_receiver != null) { if (_receiver.IsStarted) { _receiver.Stop(); } _receiver = null; } }
/// <inheritdoc /> public override void Dispose() { base.Dispose(); _tcpClient.Disconnect(); _tcpClient.Dispose(); }
public async Task Start_StartServerAndConnectWithOneClient_Successful() { var ipAddress = "127.0.0.1"; var port = 8000; var expectedClientConnectedCount = 1; var clientConnectedCount = 0; void ClientConnected(object?sender, ConnectionEventArgs e) { clientConnectedCount++; } using var simpleTcpServer = new SimpleTcpServer($"{ipAddress}:{port}"); simpleTcpServer.Start(); simpleTcpServer.Events.ClientConnected += ClientConnected; using var simpleTcpClient = new SimpleTcpClient($"{ipAddress}:{port}"); simpleTcpClient.Connect(); simpleTcpClient.Send("test"); simpleTcpClient.Disconnect(); await Task.Delay(10); simpleTcpServer.Events.ClientConnected -= ClientConnected; simpleTcpServer.Stop(); Assert.AreEqual(expectedClientConnectedCount, clientConnectedCount); }
static void Main(string[] args) { if (args.Length < 2) { ShowHelp(); } // No real checks, sends the command to the server blindly. // Server will expect P1-P8, END try { var serverPort = args[0]; var command = args[1]; var server = serverPort.Split(':')[0]; var port = int.Parse(serverPort.Split(':')[1]); var client = new SimpleTcpClient().Connect(server, port); client.WriteLine(command); client.Disconnect(); } catch (Exception ex) { Console.WriteLine(ex); } }
/// <inheritdoc cref="IServerConnection"/> public void Disconnect() { if (!Client.IsConnected) { return; } Client.Disconnect(); }
private void killSocket() { //Shutdown the socket gracefully. try { client.Disconnect(); connectionButton.Text = TCP_TEXT_START; } catch (Exception ex) { //nothing to do here. } }
private void CloseConnection(bool byUser) { disconnectTimer.Stop(); if (client != null) { client.Disconnect(); } Callbacks.Clear(); InvokeOutput("Client Disconnected."); OnDisconnected?.Invoke(byUser); }
public void StartTCPGPS() { Console.Write("start tcp"); //Debug.Print("start tcp"); client.Disconnect(); client.StringEncoder = Encoding.UTF8; try { client.Connect(tcp_server, Int32.Parse(tcp_port)); } catch { } Console.Write("connect"); client.DataReceived += DataRcv; //stripPortGPS.Text = tcp_server + " " + tcp_port; //stripPortGPS.ForeColor = Color.ForestGreen; }
private void LoginWindow_FormClosing(object sender, FormClosingEventArgs e) { if (client.TcpClient.Connected) { dynamic disconnectJson = new JObject(); disconnectJson.command = "DISCONNECT"; client.WriteLine(disconnectJson.ToString(Formatting.None)); client.Disconnect(); } }
public void Stop() { switch (who) { case "host": server.Stop(); break; case "client": client.Disconnect(); break; } }
static void Main(string[] args) { var client = new SimpleTcpClient().Connect("10.10.10.5", 3490); Console.WriteLine("Enter command ..."); ConsoleKeyInfo key_input = Console.ReadKey(); while (key_input.Key != ConsoleKey.Escape) { switch (key_input.Key) { case ConsoleKey.W: { client.Write(rasp_cmds[(int)eRaspCommands.RASP_TKCTRL_START]); break; } case ConsoleKey.S: { client.Write(rasp_cmds[(int)eRaspCommands.RASP_TKCTRL_STOP]); break; } case ConsoleKey.A: { client.Write(rasp_cmds[(int)eRaspCommands.RASP_TKCTRL_LEFT]); break; } case ConsoleKey.D: { client.Write(rasp_cmds[(int)eRaspCommands.RASP_TKCTRL_RIGHT]); break; } case ConsoleKey.Backspace: { client.Write(rasp_cmds[(int)eRaspCommands.RASP_SRV_SHUTDOWN]); break; } default: break; } key_input = Console.ReadKey(); } client.Write(rasp_cmds[(int)eRaspCommands.RASP_SRV_DISCONNECT]); client.Disconnect(); }
private void Button_Click(object sender, RoutedEventArgs e) { if ((sender as Button).Content == "Odpojit") { (sender as Button).Content = "Připojit"; OutputBox.Text += "Odpojeno!\n"; JmenoBox.IsReadOnly = false; client.Write(JmenoBox.Text + " se odpojil."); client.Disconnect(); } else { try { client.Connect(IPBox.Text, int.Parse(PortBox.Text)); client.StringEncoder = Encoding.UTF8; (sender as Button).Content = "Odpojit"; OutputBox.Text += "Připojeno!\n"; JmenoBox.IsReadOnly = true; client.Write(JmenoBox.Text + " se připojil."); } catch { OutputBox.Text += "Nelze se připojit!\n"; } } //if client. /* * OutputBox.Text = ""; * OutputBox.IsReadOnly = true; * * string textToSend = "TestString"; * * //---create a TCPClient object at the IP and port no.--- * client = new TcpClient(IPBox.Text, int.Parse(PortBox.Text)); * nwStream = client.GetStream(); * OutputBox.Text += "Připojeno\n"; * * * //---read back the text--- * byte[] bytesToRead = new byte[client.ReceiveBufferSize]; * int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize); * OutputBox.Text+=("Received : " + Encoding.ASCII.GetString(bytesToRead, 0, bytesRead) +"\n"); * //Console.ReadLine(); * client.Close(); * OutputBox.Text += "Odpojeno\n"; */ }
public void deco() { UnityThread.executeInUpdate(() => { listPlayer.Add(new Mage(10)); }); if (cli != null) { cli.Disconnect(); Instantiate(burst); burst.Play(); audManager.PlayOneShot(decoSound); } }
private void Client_DataReceived(object sender, SimpleTCP.Message e) { textStatus.Invoke((MethodInvoker) delegate() { if (e.MessageString.Contains("#N#A#M#E#")) { serverName = e.MessageString.Split(' ')[1]; } else { if (!e.MessageString.Contains("Connection terminated by Server")) { textStatus.Text += serverName; } textStatus.Text += e.MessageString + System.Environment.NewLine; if (e.MessageString.Contains("Connection terminated by Server")) { client.Disconnect(); btnConnect.Enabled = true; btnStop.Enabled = false; } } }); }
private void Dashboard_FormClosing(object sender, FormClosingEventArgs e) { timerThreadSwitch = false; try { server.Stop(); } catch { } try { client.Disconnect(); } catch { } }
public void StartServer(string ip = "127.0.0.1", int port = 53399) { try { if (Client == null) { Client = new SimpleTcpClient().Connect(ip, port); } else { Client.Disconnect(); Client.Dispose(); Client = new SimpleTcpClient().Connect(ip, port); } } catch (Exception e) { Server.SetInfoText($"ServerERR: {e.Message}"); } }
private void btDisconnect_Click(object sender, EventArgs e) { //Desconecta o cliente do servidor if (client.IsConnected) { try { client.Disconnect(); btSend.Enabled = false; btConnect.Enabled = true; } catch (Exception ex) { MessageBox.Show(ex.Message, "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } else { MessageBox.Show("Precisa estar conectado para desconectar.", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
public void Connect() { try { var r = Client?.TcpClient.Connected; if (r != true) { if (Client != null) { Client.Disconnect(); Client.Dispose(); } Client = new SimpleTcpClient().Connect(Properties.Settings.Default.CAMERA_IP, Properties.Settings.Default.CAMERA_PORT); } } catch (SocketException ex) { Events.Publish(new MsgItem { Level = "E", Time = DateTime.Now, Value = ex.Message }); } }
public static void Main() { SetProcessDPIAware(); try { client = new SimpleTcpClient().Connect("139.129.4.219", 8082); client.StringEncoder = System.Text.UnicodeEncoding.UTF8; client.Delimiter = System.Convert.ToByte('\n'); client.DelimiterDataReceived += (sender, msg) => { Console.WriteLine(msg.MessageString); if (msg.MessageString.Contains("无法解析的命令")) { MessageBox.Show("Command can't be parsed!"); } JObject obj = JObject.Parse(msg.MessageString); if ((string)obj["event"] == "ip_duplicate") { MessageBox.Show("相同IP已有人登录,你被迫下线,请更换网络后重试"); System.Environment.Exit(0); } else if (obj["success"] != null && !(bool)obj["success"]) { MessageBox.Show(obj.Property("reason").Value.ToString()); } }; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new BeginDialog()); client.Disconnect(); } catch (SocketException) { MessageBox.Show("连接服务器失败,请重试"); } }
private void startButton_Click(object sender, EventArgs e) { if (client.IsConnected) { client.Disconnect(); theForm.label5.Text = "down"; theForm.label5.ForeColor = System.Drawing.Color.Red; return; } theForm.messages.Items.Add(" deez nuts has joined."); // set events client.Events.Connected += Connected; client.Events.Disconnected += Disconnected; client.Events.DataReceived += DataReceived; try { client.Connect(); } catch (System.Net.Sockets.SocketException) { _ = MessageBox.Show("Server is down / or you don't have internet", "This isn't epic", MessageBoxButtons.OK, MessageBoxIcon.Error); theForm.label5.Text = "down"; theForm.label5.ForeColor = System.Drawing.Color.Red; } }
private void button2_Click(object sender, EventArgs e) { if (gameType == 3) { if (f == null) { client.Disconnect(); this.Close(); } else if (!f.IsDisposed) { f.Close(); client.Disconnect(); this.Close(); } else { client.Disconnect(); this.Close(); } } else { if (g == null) { client.Disconnect(); this.Close(); } else if (!g.IsDisposed) { g.Close(); client.Disconnect(); this.Close(); } else { client.Disconnect(); this.Close(); } } }
private void BtnClose_Click(object sender, EventArgs e) { engraver.Disconnect(); this.Close(); }
public static void KeepAlive() { string ver = Version.FileVersion; Connect(); while (Running) { if ((DateTime.Now - StartupTime).Hours > 10) { IsShuttingDown = true; } var infoGathered = false; if (Games == null || (IsShuttingDown && Games.Count == 0)) { Thread.Sleep(5000); //Running = false; Environment.Exit(0); return; } //monitor the tcp connection to keep it open try { if (Games == null) { //uhhhhhhhhh ok..... continue; } var games = Games.ToList(); var info = new NodeInfo { Games = new HashSet <GameInfo>(), ClientId = ClientId, CurrentGames = games.Count, CurrentPlayers = games.Sum(x => x?.Players?.Count ?? 0), DuplicateGamesRemoved = DupGamesKilled, ThreadCount = 0,//Process.GetCurrentProcess().Threads.Count, //TotalGames = GamesStarted, //TotalPlayers = games.Sum(x => x.Players?.Count ?? 0) + TotalPlayers, Uptime = DateTime.Now - StartupTime, Version = ver, ShuttingDown = IsShuttingDown, MessagesSent = MessagesSent }; foreach (var g in games) { if (g.Players == null) { Games.Remove(g); continue; } var gi = new GameInfo { Language = g.Language, ChatGroup = g.ChatGroup, GroupId = g.ChatId, NodeId = ClientId, State = g.IsRunning ? GameState.Running : g.IsJoining ? GameState.Joining : GameState.Dead, Users = g.Players != null ? new HashSet <int>(g.Players.Where(x => !x.IsDead).Select(x => x.TeleUser.Id)) : new HashSet <int>(), PlayerCount = g.Players?.Count ?? 0 //Players = new HashSet<IPlayer>(g.Players) }; info.Games.Add(gi); } var json = JsonConvert.SerializeObject(info); infoGathered = true; Client.WriteLine(json); } catch (Exception e) { while (e.InnerException != null) { e = e.InnerException; } Console.WriteLine($"Error in KeepAlive: {e.Message}\n{e.StackTrace}\n"); if (infoGathered) //only disconnect if tcp error { if (Client != null) { try { Client.DataReceived -= ClientOnDataReceived; Client.DelimiterDataReceived -= ClientOnDelimiterDataReceived; Client.Disconnect(); } catch { // ignored } } Connect(); } } Thread.Sleep(500); } }
// Ham nhan tat ca moi thu phan hoi ve private void Client_DataReceived(object sender, SimpleTCP.Message e) { MessageBox.Show(e.MessageString); client.Disconnect(); client.Dispose(); }
static void Main(string[] args) { _ServerIp = InputString("Server IP :", "127.0.0.1", false); _ServerPort = InputInteger("Server Port :", 9000, true, false); /* * _Ssl = InputBoolean("Use SSL :", false); * * if (_Ssl) * { * _PfxFilename = InputString("PFX Certificate File:", "simpletcp.pfx", false); * _PfxPassword = InputString("PFX File Password:"******"simpletcp", false); * } * * _Client = new SimpleTcpClient(_ServerIp, _ServerPort, _Ssl, _PfxFilename, _PfxPassword); */ // _Client = new SimpleTcpClient((_ServerIp + ":" + _ServerPort)); _Client = new SimpleTcpClient(_ServerIp, _ServerPort); _Client.Events.Connected += Connected; _Client.Events.Disconnected += Disconnected; _Client.Events.DataReceived += DataReceived; _Client.Keepalive.EnableTcpKeepAlives = true; _Client.Settings.MutuallyAuthenticate = false; _Client.Settings.AcceptInvalidCertificates = true; _Client.Settings.ConnectTimeoutMs = 5000; _Client.Logger = Logger; // _Client.Connect(); _Client.ConnectWithRetries(5000); while (_RunForever) { string userInput = InputString("Command [? for help]:", null, false); switch (userInput) { case "?": Menu(); break; case "q": case "Q": _RunForever = false; break; case "c": case "C": case "cls": Console.Clear(); break; case "send": Send(); break; case "sendasync": SendAsync(); break; case "connected": IsConnected(); break; case "dispose": _Client.Dispose(); break; case "stats": Console.WriteLine(_Client.Statistics.ToString()); break; case "connect": _Client.Connect(); break; case "disconnect": _Client.Disconnect(); break; case "stats reset": _Client.Statistics.Reset(); break; } } }
public async Task Start_StartServerAndConnectWithOneClientAndSendMessages_Successful() { var ipAddress = "127.0.0.1"; var port = 8000; var testData = StringHelper.RandomString(1000); var acknowledgeData = Encoding.UTF8.GetBytes("acknowledge"); var serverReceiveError = false; var serverReceiveData = false; var clientReceiveError = false; var clientReceiveData = false; var expectedClientConnectedCount = 1; var clientConnectedCount = 0; void ServerClientConnected(object?sender, ConnectionEventArgs e) { clientConnectedCount++; } void ServerDataReceived(object?sender, DataReceivedEventArgs e) { serverReceiveData = true; var receivedData = Encoding.UTF8.GetString(e.Data); Trace.WriteLine($"{nameof(ServerDataReceived)} - {receivedData}"); if (testData != receivedData) { serverReceiveError = true; } if (sender is SimpleTcpServer simpleTcpServer) { simpleTcpServer.Send(e.IpPort, acknowledgeData); } } void ClientDataReceived(object?sender, DataReceivedEventArgs e) { clientReceiveData = true; var receivedData = Encoding.UTF8.GetString(e.Data); Trace.WriteLine($"{nameof(ClientDataReceived)} - {receivedData}"); if (!Enumerable.SequenceEqual(e.Data, acknowledgeData)) { clientReceiveError = true; } } using var simpleTcpServer = new SimpleTcpServer($"{ipAddress}:{port}"); simpleTcpServer.Start(); simpleTcpServer.Events.ClientConnected += ServerClientConnected; simpleTcpServer.Events.DataReceived += ServerDataReceived; using var simpleTcpClient = new SimpleTcpClient($"{ipAddress}:{port}"); simpleTcpClient.Connect(); simpleTcpClient.Events.DataReceived += ClientDataReceived; for (var i = 0; i < 10; i++) { simpleTcpClient.Send(testData); await Task.Delay(100); } simpleTcpClient.Events.DataReceived -= ClientDataReceived; simpleTcpClient.Disconnect(); await Task.Delay(10); simpleTcpServer.Events.ClientConnected -= ServerClientConnected; simpleTcpServer.Events.DataReceived -= ServerDataReceived; simpleTcpServer.Stop(); Assert.AreEqual(expectedClientConnectedCount, clientConnectedCount); Assert.IsTrue(serverReceiveData, "Server receive no data"); Assert.IsFalse(serverReceiveError, "Server receive error detected"); Assert.IsTrue(clientReceiveData, "Client receive no data"); Assert.IsFalse(clientReceiveError, "Client receive error detected"); }
public void Disconnect() { client.Disconnect(); }