A super simple TCP communication package in C#: step by step guide

A super simple TCP communication package in C#: step by step guide

Hey, fellow developers! Today we are going to talk about TCP communication in C#. TCP (Transmission Control Protocol) is a connection-oriented, reliable, byte-stream-based transport layer communication protocol. In many application scenarios, we need to use TCP to achieve data transmission between the client and the server. Don't worry, even if you are a novice in TCP communication, I will use the simplest and most colloquial way to take you step by step to implement a basic TCP communication package.

1. Preparation

Before you begin, make sure you have installed Visual Studio (or another IDE that supports C#) in your development environment and created a new C# console project.

2. Create a server

First, let's implement a simple TCP server. This server will listen on a specific port, wait for client connections, and return a response after receiving a message.

  • Add the necessary namespaces At the top of your server code file, add the following namespace:
 using System; using System.Net; using System.Net.Sockets; using System.Text;
  • Implementing the server logic Next, we write the server code in the Main method:
 class Program { static void Main(string[] args) { // 定义一个IP地址和端口号IPAddress ipAddress = IPAddress.Parse("127.0.0.1"); int port = 11000; // 创建TCP监听器TcpListener listener = new TcpListener(ipAddress, port); try { // 启动监听listener.Start(); Console.WriteLine("服务器已启动,等待连接..."); while (true) { // 接受客户端连接TcpClient client = listener.AcceptTcpClient(); Console.WriteLine("客户端已连接!"); // 获取网络流NetworkStream stream = client.GetStream(); // 读取客户端发送的数据byte[] buffer = new byte[256]; int bytesRead = stream.Read(buffer, 0, buffer.Length); string receivedData = Encoding.ASCII.GetString(buffer, 0, bytesRead); Console.WriteLine($"收到消息: {receivedData}"); // 发送响应消息byte[] response = Encoding.ASCII.GetBytes("消息已收到!"); stream.Write(response, 0, response.Length); // 关闭连接client.Close(); } } catch (SocketException e) { Console.WriteLine($"SocketException: {e}"); } finally { // 停止监听listener.Stop(); } Console.WriteLine("\n按任意键退出..."); Console.ReadKey(); } }

3. Create a client

Next, we will implement a simple TCP client that will connect to the server, send a message, and receive a response from the server.

  • Add the necessary namespaces At the top of your client code file, add the following namespace:
 using System; using System.Net.Sockets; using System.Text;
  • Implementing the client logic Next, we write the client code in the Main method:
 class Program { static void Main(string[] args) { // 定义一个服务器IP地址和端口号string server = "127.0.0.1"; int port = 11000; try { // 创建TCP客户端TcpClient client = new TcpClient(server, port); Console.WriteLine("已连接到服务器!"); // 获取网络流NetworkStream stream = client.GetStream(); // 发送消息到服务器string message = "你好,服务器!"; byte[] data = Encoding.ASCII.GetBytes(message); stream.Write(data, 0, data.Length); Console.WriteLine($"发送消息: {message}"); // 接收服务器的响应byte[] buffer = new byte[256]; int bytesRead = stream.Read(buffer, 0, buffer.Length); string responseData = Encoding.ASCII.GetString(buffer, 0, bytesRead); Console.WriteLine($"收到响应: {responseData}"); // 关闭连接stream.Close(); client.Close(); } catch (ArgumentNullException e) { Console.WriteLine($"ArgumentNullException: {e.Message}"); } catch (SocketException e) { Console.WriteLine($"SocketException: {e.Message}"); } Console.WriteLine("\n按任意键退出..."); Console.ReadKey(); } }

4. Run the test

Now that you have completed the server and client code, let's run it and see the effect.

  • Run the server First, run your server code. You will see the console output "Server started, waiting for connections...".
  • Run the Client Then, run your client code. You should see the console output "Connected to server!", the message sent, and the response received from the server.
  • Observe the results on the server side, you will see the console output "Client connected!" and "Received message: Hello, server!".

V. Conclusion

Through the above steps, you have successfully implemented a simple TCP communication package. The server will listen to a port, wait for the client to connect, and return a response after receiving the message. The client will connect to the server, send a message, and receive the server's response.

This is just a basic implementation, you can expand and optimize it, such as adding multi-threading support, exception handling, data format processing, etc. I hope this article is helpful to you, and I wish you happy programming!

<<:  What you need to know about HTTP protocol

>>:  University of Nottingham Ningbo China: seamlessly connected to the world, with top 100 universities within easy reach

Blog    

Recommend

Yunnan Yuxi and Huawei Enterprise Cloud deepen cooperation

On March 30, 2017, the People's Government of...

How to increase the speed of the router

[[183829]] How to increase the speed of the route...

5G is so good, but how many people can afford the data charges?

In the past 2019, with the issuance of 5G commerc...

Tomorrow’s 5G performance depends on today’s mobile edge

We have been hearing the hype about 5G for quite ...

2018 Yunnan-Huawei Software Industry Summit was held on December 20

The 2018 Yunnan-Huawei Software Industry Summit w...

CloudCone Easter Sale: Los Angeles KVM Annual Payment Starting at $12.95

CloudCone's Easter promotion started on the m...

After 5G, there will be no more "operators", what do you think?

As the name implies, the core capability of opera...

RF chip, a pearl in 5G mobile phone

According to statistics, in the fourth quarter of...

In the global 5G competition, who will be the ultimate beneficiary?

Leifeng.com: To understand cellular technology, y...