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

Recommend

Why choose NB-IoT when there are so many standards?

The need for communication is indispensable in ou...

5G will catalyze the era of large-scale innovation in the whole society

Intuitively, 5G has a very obvious role in drivin...

...

5 Things That Can Slow Down Your Wi-Fi Network

Wi-Fi networks can be slow due to the use of olde...

Blockchain development faces four major "pain points"

Not long ago, the central bank and seven other mi...

802.11be (Wi-Fi 7) Technology Outlook

1. Overview of Wi-Fi 7 New Features Figure 1 is a...

Dr. Li Jin: Is building credibility “regardless of cost”?

[51CTO.com original article] June in Beijing is w...

H3C Launches Telecom-Grade Cloud Platform at MWC Shanghai

On June 28, H3C Group made its debut at the Asian...