TcpClient client = new TcpClient("localhost", 1234); NetworkStream stream = client.GetStream(); byte[] data = Encoding.UTF8.GetBytes("Hello Server!"); stream.Write(data, 0, data.Length);
TcpClient client = new TcpClient("localhost", 1234); NetworkStream stream = client.GetStream(); byte[] data = new byte[1024]; int bytesRead = stream.Read(data, 0, 1024); string message = Encoding.UTF8.GetString(data, 0, bytesRead); Console.WriteLine(message);In this example, we create a TcpClient object and connect to a server running on the localhost on port 1234. We then call the GetStream method to retrieve the NetworkStream object and create a byte array to store the received data. We then call the Read method to read the data from the NetworkStream into the byte array and convert the byte array to a string using the UTF-8 encoding. Finally, we print the received message to the console. The package library used in these examples is System.Net.Sockets.