//-------------------------------------------------------------- // METHODE ENVOIE DU MESSAGE //-------------------------------------------------------------- private void BtnSend_Click(object sender, EventArgs e) { if (client.IsConnected) //si le client est connecté { if (!string.IsNullOrEmpty(txtMessage.Text)) //si il y a quelque chose d'écrit { client.Send("M" + txtMessage.Text); //on envoie le message txtInfo.Text += $"Me:{txtMessage.Text}{Environment.NewLine}"; txtMessage.Text = string.Empty; } if ((checkdynamique.Checked && checkstatique.Checked) || ((checkdynamique.Checked == false) && (checkstatique.Checked == false))) //gère l'erreur sur les checkbox { MessageBox.Show("vous devez choisir entre un des deux modes! "); } else if ((!string.IsNullOrEmpty(txtspeed.Text)) && (!string.IsNullOrEmpty(txttorque.Text))) { if (checkdynamique.Checked) //si le client veut en dynamique { smode = "dynamic"; } if (checkstatique.Checked) //si le client veut en statique { smode = "static"; } try // vérifie que la vitesse est un entier { double x = Convert.ToDouble(txtspeed.Text); } catch { MessageBox.Show("Vous devez entrer un entier"); } //envoie vitesse en rajoutant S devant le string pour reconnaissance par le serveur sV = "S" + txtspeed.Text; txtInfo.Text += $"Me:speed={txtspeed.Text}{Environment.NewLine}"; txtspeed.Text = string.Empty; //envoie couple de charge en rajoutant T devant le string pour reconnaissance par le serveur sT = "T" + txttorque.Text; txtInfo.Text += $"Me:torque={ txttorque.Text}{Environment.NewLine}"; //écriture du couple de charge dans boîte de dialogue txttorque.Text = string.Empty; client.Send(smode + sV + sT); //envoie de la chaîne sous forme mode+S+vitesse+T+vitesse } else //si il manque une donnée { MessageBox.Show("vous devez entrer une vitesse et un couple de charge "); } } }
public void SendData(byte[] data) { if (data != null) { _Client.Send(data); } }
SimpleTcpClient client; // Declarando classe SimpleTCP para fazer as conecções dos sockets. private void btnSend_Click(object sender, EventArgs e) { btnSend.Enabled = false; if (client.IsConnected) { string[] linhas1 = File.ReadAllText("Prova Estagio DEV - Anexo 1.txt").Split('\n', ';'); // Ler e transformar o txt em um array do tipo string dividido pelas linhas e ';'. List <string> linhas = new List <string>(); for (int i = 0; i < linhas1.Length; i++) // Estrutura de repetição feita para percorrer todo o array e adicionar os nomes da categoria '1' em uma lista separada. { if (linhas1[i] == "1" || linhas1[i] == "1\r") // Lógica para selecionar os nomes da categoria '1' dentro do array criado. { linhas.Add(linhas1[i - 1]); // Adicionar os nomes da categoria '1' para uma lista. } } foreach (string linha in linhas) { if (!string.IsNullOrEmpty(linha)) { client.Send(linha + "\n"); // Enviar os nomes do arquivo .txt da lista para a outra aplicação. } } txtInfo.Text += $"(Master) Listas de nomes lida e enviada! {Environment.NewLine}"; } }
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 Send() { string data = InputString("Data:", "Hello!", true); if (!String.IsNullOrEmpty(data)) { _Client.Send(data); } }
/// <inheritdoc cref="IServerConnection"/> public void Send(byte[] data) { if (!IsConnected) { return; } lock (lockObject) { Client.Send(data); } }
private void btnSend_Click(object sender, EventArgs e) { if (client.IsConnected) { if (!string.IsNullOrEmpty(txtInfo.Text)) { client.Send(txtMessage.Text); txtInfo.Text += $"Me : {txtMessage.Text}{Environment.NewLine}"; txtMessage.Text = string.Empty; } } }
//public event EventHandler<DataReceivedEventArgs> DataReceived; public TCPConnection(string destination) { _client = new SimpleTcpClient(destination); _client.Events.Connected += ConnectedEventHandler; _client.Events.Disconnected += DisconnectedEventHandler; _client.Events.DataReceived += DataReceivedEventHandler; _client.Keepalive = new SimpleTcpKeepaliveSettings() { EnableTcpKeepAlives = true, TcpKeepAliveInterval = 1, TcpKeepAliveTime = 1, TcpKeepAliveRetryCount = 3 }; ReadStream.ReadTimeout = 1500; WriteStream = new InterceptableWriteMemoryStream(bytes => _client.Send(bytes)); }
// sending to current IP address: current port number public void sendMessage(string IP_Port, string message) { if (!string.IsNullOrEmpty(message)) { if (server != null) { server.Send(IP_Port, message); } else { client.Send(message); } } }
/// <summary> /// Send any coordinates using SuperSimpleTcp's nifty implementation. /// </summary> /// <param name="coords">The coordinates to send.</param> public void Send(string coords) { try { client.Send(coords); shouldShowPeerError = true; } catch { if (shouldShowPeerError) { shouldShowPeerError = false; Core.Log("Failed to send coords to peer! Are the IP and port set correctly?", false); } } }
public void send <T>(MessageBase message) where T : MessageBase { using (var outputStream = new MemoryStream()) { using (var bw = new BinaryWriter(outputStream)) { byte[] data = JsonSerializer.SerializeToUtf8Bytes((T)message, sOption); outputStream.Capacity = data.Length + 4; bw.Write(data.Length); bw.Write(data); outputStream.Position = 0; client.Send(outputStream.Length, outputStream); Console.WriteLine($"{outputStream.Length} bytes sent to server."); } } }
/// <summary> /// On button Send to the server /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void buttonSend_Click(object sender, EventArgs e) { string err = ""; if (bConnected) { if (!client.Send(textBox_Send.Text + GetEOL(), out err)) { MessageBox.Show("Error while sending to server: " + err, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { MessageBox.Show("Not connected to the server!", "WARNING", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void Window_Closing(object sender, EventArgs e) { //Change the IsLogged to 0 //Send disconnect to server with username Console.WriteLine("Window_Closing was called."); SqlConnection sqlConnection = DBService.Get_DB_Connection(); string QUERY = "UPDATE db_Clients SET IsLogged=0 WHERE Username=@Username"; SqlCommand sqlComm = new SqlCommand(QUERY, sqlConnection); sqlComm.Parameters.AddWithValue("@Username", user.username); sqlComm.ExecuteNonQuery(); DBService.Close_DB_Connection(); client.Send($"disconnect|{user.username}"); }
/** * Data manipulation */ public void SendGameData() { /** * Serialize the game data and send to the server */ try { client.Send(JsonConvert.SerializeObject(new Game())); } catch (Exception e) { MessageBox.Show( "Data se ńepodařilo odeslat: " + e.Message, "Chyba spojení", MessageBoxButtons.OK, MessageBoxIcon.Error ); } }
private void btnSend_Click(object sender, EventArgs e) { string insertQuery = "INSERT INTO member_tb(IP,Message) VALUES('" + txtIP.Text + "'," + txtMessage.Text + ")"; //member_tb2테이블에 IP,Message값을 INSERT한다. connection.Open(); MySqlCommand command = new MySqlCommand(insertQuery, connection); try//예외 처리 { // 만약에 내가처리한 Mysql에 정상적으로 들어갔다면 메세지를 보여주라는 뜻이다 if (command.ExecuteNonQuery() == 1) { MessageBox.Show("정상적으로 갔다"); } else { MessageBox.Show("비정상 이당"); } } catch (Exception ex) { MessageBox.Show(ex.Message); } connection.Close(); if (client.IsConnected) { if (!string.IsNullOrEmpty(txtMessage.Text)) { client.Send(txtMessage.Text); txtInfo.Text += $"Me: {txtMessage.Text}{Environment.NewLine}"; txtMessage.Text = string.Empty; string hexString = "8E2"; int num = Int32.Parse(hexString, System.Globalization.NumberStyles.HexNumber); Console.WriteLine(num); } } }
private void btSend_Click(object sender, EventArgs e) { //Envia a mensagem para o servidor e ele propaga para todos os clientes if (client.IsConnected) { if (!string.IsNullOrEmpty(txtMessage.Text)) { client.Send(txtMessage.Text); txtInfo.Text += $"Eu {GetFormattedTimestamp()}: {txtMessage.Text}{Environment.NewLine}"; txtInfo.Text += string.Empty; txtMessage.Text = string.Empty; } else { MessageBox.Show("Digite alguma mensagem para ser enviada.", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } else { MessageBox.Show("Algo deu errado ao se comunicar com o servidor.", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public static void SendAsJson <T>(this SimpleTcpClient client, T obj) => client.Send(Utf8Json.JsonSerializer.Serialize(obj));
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 OnClick(View v) { string err; if (v.Id == Resource.Id.btnClearFromServer) { et_SendToServer.Text = ""; } else if (v.Id == Resource.Id.btnClear) { tv_Info.Text = ""; } else if (v.Id == btn_Connect.Id) { bool bError = true; string s = "Unknown error"; if (!bConnected) { // try to connect if (client.Connect(et_IP.Text, Convert.ToInt16(et_Port.Text), 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) { Toast.MakeText(this, s, ToastLength.Short).Show(); } tv_Info.Text += "DEBUG > " + s + "\r\n"; btn_Connect.Text = bConnected ? "DISCONNECT" : "CONNECT"; SetGUIstate(bConnected); } else if (v.Id == btn_Send.Id) { err = ""; if (bConnected) { if (!client.Send(et_SendToServer.Text + GetEOL(), out err)) { Toast.MakeText(this, "Error while sending to server: " + err, ToastLength.Long).Show(); } } else { Toast.MakeText(this, "Not connected to the server!", ToastLength.Long).Show(); } } }
private void Events_DataReceived(object sender, DataReceivedEventArgs e) { switch (Encoding.UTF8.GetString(e.Data).Split(':')[0]) { case Messages.Server.Start: this.Invoke((MethodInvoker) delegate { this.Hide(); gameForm = new GameForm(Encoding.UTF8.GetString(e.Data).Split(':')[1], this); gameForm.Text = this.Text; gameForm.Show(); }); break; case Messages.Client.Move: this.Invoke((MethodInvoker) delegate { gameForm.statusLabel.Text = "TWOJA TURA"; gameForm.enemyMoveFromServer(Int32.Parse(Encoding.UTF8.GetString(e.Data).Split(':')[1])); }); break; case Messages.Server.Cancel: break; case Messages.Server.Disconnect: MessageBox.Show("Błędny login lub hasło", "Login ERROR"); client.Disconnect(); loginFormsVisible(true); this.Invoke((MethodInvoker) delegate { this.Text = " "; }); break; case Messages.Server.User: this.Invoke((MethodInvoker) delegate { this.Text += $" W->{ Encoding.UTF8.GetString(e.Data).Split(':')[1]} P->{Encoding.UTF8.GetString(e.Data).Split(':')[2]}"; }); break; case Messages.Server.Registered: MessageBox.Show("Konto zostało stworzone", "Registered"); break; case Messages.Server.Matches: this.Invoke((MethodInvoker) delegate { String[] matches = Encoding.UTF8.GetString(e.Data).Split(':'); listBoxMatches.Items.Clear(); for (int i = 1; i < matches.Length; i++) { listBoxMatches.Items.Add($"{matches[i]}"); } }); break; case Messages.Server.Logged: MessageBox.Show("Taki gracz jest już zalogowany", "Login ERROR"); client.Disconnect(); loginFormsVisible(true); this.Invoke((MethodInvoker) delegate { this.Text = " "; }); break; case Messages.Server.Winner: this.Invoke((MethodInvoker) delegate { gameForm.Close(); this.Show(); this.joinButton.Enabled = true; this.buttonRefresh.Enabled = true; }); client.Send(Messages.Client.SaveGame + ":" + Encoding.UTF8.GetString(e.Data).Split(':')[1] + ":" + Encoding.UTF8.GetString(e.Data).Split(':')[2] + ":" + Encoding.UTF8.GetString(e.Data).Split(':')[3]); MessageBox.Show("Wygrał gracz - " + Encoding.UTF8.GetString(e.Data).Split(':')[3], "Koniec Gry"); break; case Messages.Server.Lost: this.Invoke((MethodInvoker) delegate { this.Show(); this.joinButton.Enabled = true; this.buttonRefresh.Enabled = true; this.client.Send(Messages.Server.Cancel); }); this.Invoke((MethodInvoker) delegate { gameForm.Close(); }); MessageBox.Show("Przegrana! Wygrał gracz - " + Encoding.UTF8.GetString(e.Data).Split(':')[1], "Koniec Gry"); break; } }
public void Send(string msg) { sock.Send(Encoding.Default.GetBytes(msg)); }
/// <summary> /// 发送数据包 /// </summary> /// <param name="packet"></param> public void Send(MainPacket <T> packet) { Client.Send(packet); }
private void hostButton_Click(object sender, EventArgs e) { client.Send(Messages.Client.Host); }