📜  c# connect tcp - C# (1)

📅  最后修改于: 2023-12-03 14:59:39.828000             🧑  作者: Mango

C# Connect TCP

In C#, connecting to a TCP server can be accomplished using the TcpClient class. This class provides a simple way to create a TCP connection, send and receive data.

Creating a TCP Connection

To create a TCP connection, first, create an instance of TcpClient class, and then connect it to the server using the Connect() method. Here is an example:

TcpClient client = new TcpClient();
client.Connect("127.0.0.1", 8080); // connect to server at IP address 127.0.0.1 and port 8080
Sending and Receiving Data

Once a connection is established, data can be sent and received using the NetworkStream class. The TcpClient class has a property named GetStream() that returns a NetworkStream object. Data can be sent by writing to the stream using the Write() method, and received data can be read from the stream using the Read() method.

Here is an example of sending data to the connected server:

NetworkStream stream = client.GetStream();
byte[] data = Encoding.UTF8.GetBytes("Hello, server!");
stream.Write(data, 0, data.Length);

And here is an example of receiving data from the server:

byte[] buffer = new byte[1024];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received message from server: " + message);
Closing the Connection

After use, it is important to properly close the connection to the server. This can be accomplished by calling the Close() method on both the TcpClient and NetworkStream objects.

stream.Close();
client.Close();
Conclusion

In this tutorial, we learned how to connect to a TCP server using C# and the TcpClient class. We also learned how to send and receive data using the NetworkStream class, and how to properly close the connection.