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

The legend of network protocols (Part 2): TCP emerges

This section will formally enter the content of n...

With the launch of 5G and Wi-Fi 6, where will wireless network products go?

Today, topics about 5G and Wi-Fi are endless, and...

GSMA Liu Hong: Who will build the 5G private network? Let the operators do it

[[383535]] 5G has the characteristics of high spe...

F5 Future

[51CTO.com original article] Expert introduction:...

The story of spectrum: Gigabit is just the beginning

At the end of 4G development, the most advanced m...

6 trends that will boost the impact of IoT in 2018

In 2016-2017, the trend of IoT was widely accepte...

Wi-Fi 6 certification, here are 6 issues worth paying attention to!

This article is reproduced from Leiphone.com. If ...

AT&T to use open source SDN technology to prove 5G

As the next generation of mobile communication te...

8 predictions for the development of network technology in 2017

The Internet is evolving at an unprecedented pace...

CCS Insight: 5G connections to jump to 3.2 billion by the end of 2025

The GSMA's in-house The Mobile Economy Report...