using System; using System.Net; using System.Net.Sockets; using System.Text; class Program { static void Main() { IPAddress serverIp = IPAddress.Parse("192.168.0.1"); int serverPort = 8080; string message = "Hello server!"; TcpClient client = new TcpClient(serverIp.ToString(), serverPort); NetworkStream stream = client.GetStream(); byte[] data = Encoding.ASCII.GetBytes(message); stream.Write(data, 0, data.Length); client.Close(); } }
using System; using System.Net; using System.Net.Sockets; using System.Text; class Program { static void Main() { IPAddress serverIp = IPAddress.Parse("192.168.0.1"); int serverPort = 8080; TcpClient client = new TcpClient(serverIp.ToString(), serverPort); NetworkStream stream = client.GetStream(); byte[] buffer = new byte[1024]; int bytesRead = stream.Read(buffer, 0, buffer.Length); string message = Encoding.ASCII.GetString(buffer, 0, bytesRead); Console.WriteLine("Received message: {0}", message); client.Close(); } }In this example, we create a TCP client and connect it to a server at IP address 192.168.0.1 and port number 8080. Next, we obtain the network stream of the client and create a buffer to store the incoming data. We then read from the network stream into the buffer and convert it into a string using ASCII encoding. Finally, we print the received message to the console and close the client. Both examples use the C# System.Net.Sockets library, which is part of the .NET framework.