//Hàm gửi dữ liệu void Send(object obj) { client.Send(SerializeData(obj)); }
private void SendButtonClick(object sender, RoutedEventArgs e) { _socket.Send(Encoding.UTF8.GetBytes(postcodeTextBox.Text)); ThreadPool.QueueUserWorkItem(ReceiveInfo); }
// Function to get the score of every player from the server public List <Player> GetScoreAllPlayers() { List <Player> players = new List <Player>(); // Data buffer for incoming data. byte[] bytes = new byte[1024]; // Connect to a remote device. try { var address = Dns.GetHostEntry(serverAddress).AddressList.First(ip => ip.AddressFamily == AddressFamily.InterNetworkV6); // IPV4 to IPV6 address IPAddress ipAddress = address; IPEndPoint remoteEP = new IPEndPoint(ipAddress, Int32.Parse(serverPort)); // Create a TCP/IP socket. Socket sender = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); // Connect the socket to the remote endpoint. Catch any errors. try { sender.Connect(remoteEP); // Encode the data string into a byte array. byte[] msg = Encoding.ASCII.GetBytes("<ScorePlayers>" + this.id);// Ask the score of other players // Send the data through the socket. int bytesSent = sender.Send(msg); // Receive the response from the remote device. int bytesRec = sender.Receive(bytes); string result = Encoding.ASCII.GetString(bytes, 0, bytesRec); if (result.IndexOf("<ReturnScorePlayers>") < 0) { Console.WriteLine("Server return error."); } // Release the socket. sender.Shutdown(SocketShutdown.Both); sender.Close(); // Get the answer of the server and put it on the List of players score result = result.Replace("<ReturnScorePlayers>", ""); string[] result_array = result.Split(';'); for (int i = 0; i < result_array.Length; i += 2) { players.Add(new Player(result_array[i], Int16.Parse(result_array[i + 1])));// Create a new player with its id and score and add it to the list of all players } return(players); } catch (Exception e) { Console.WriteLine("Unexpected exception : {0}", e.ToString()); } } catch (Exception e) { Console.WriteLine(e.ToString()); } return(null); }