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

8 myths about 5G

5G is the next generation of wireless broadband t...

Intelligent connectivity: the convergence of 5G with AI, IoT and AR

Although it is still too early to truly measure t...

SPI Subsystem SPI Driver

1. SPI driver source file directory Linux common ...

How to manage data center cabling?

Tracking and managing data center cabling is one ...

8 technologies that are changing IT services

No one can deny that service is a job performed b...

Introducing social capital to solve the 5G network construction dilemma

Three months after the issuance of 5G licenses, t...

Super detailed! Introduction to Ethernet switch security features

Today I will talk to you about the security funct...

Current limiting is never an easy task!

[[354146]] This article is reprinted from the WeC...

5G and machine learning: Transforming cell towers from smart to genius

[[335632]] 5G ushers in new “genius” networks to ...

How does network latency occur?

Network latency Network delay refers to the time ...