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

How to solve Wi-Fi authentication problems?

Many people have encountered this problem when co...

The 10 hottest technology keywords in 2018, every move will change the future

The end of 2017 is accompanied by the arrival of ...

BICS: 5G device connectivity unlocks new IoT use cases

BICS, a global voice operator and mobile data ser...

How to fight the emergency communication battle in the “golden 72 hours”?

Life is the most important thing, and unity is st...

IoT and 5G: A blessing or a curse?

The UK's recent decision to phase out Huawei ...

The 5G era is accelerating. When will edge computing replace "core" computing?

In the 5G era, the number of connected devices wi...

How to Choose Brite Box and White Box Switches for Your Network

In the ever-evolving network infrastructure lands...

Here is everything you want to know about 5G progress and next steps

The progress of 5G has always been a key topic of...