Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Network Communication with Sockets in C Sharp

Tech May 9 4

A Socket combines an IP address with a port number, creating an endpoint for network communication. Think of it as an electrical outlet—once you establish a Socket, other programs can connect through it over the network.

For client applications, a single Socket instance suffices. However, server applications require two Socket objects: one for listening on a designated port, and additional instances created for each connected client to handle actual data exchange.

Server-Side Implementation

The following steps outline how to set up a listening Socket on the server:

// Initialize a stream-based TCP Socket
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

// Configure the endpoint with IP and port
IPAddress localAddress = IPAddress.Parse("服务器IP地址");
IPEndPoint endpoint = new IPEndPoint(localAddress, 服务器端口);

// Bind the Socket to the network interface
listener.Bind(endpoint);

// Start listening with a connection queue
listener.Listen(backlogSize);

Once the Socket is bound and listening, spawn a dedicatde thread to accept incoming connections:

// Launch the monitoring thread
Thread monitorThread = new Thread(MonitorClients);
monitorThread.IsBackground = true;
monitorThread.Start();

// Continuous monitoring loop
private void MonitorClients()
{
    while (true)
    {
        // Create a new handler for each connecting client
        Socket clientHandler = listener.Accept();
        
        // Spawn a worker thread to process client data
        Thread workerThread = new Thread(ProcessClientData);
        workerThread.IsBackground = true;
        workerThread.Start(clientHandler);
    }
}

The worker thread receives messages from its assigned client:

private void ProcessClientData(object handler)
{
    Socket client = (Socket)handler;
    byte[] dataBuffer = new byte[bufferSize];
    
    while (client.Connected)
    {
        int bytesRead = client.Receive(dataBuffer);
        if (bytesRead > 0)
        {
            // Process received data
        }
    }
}

Client-Side Implementation

Clients establish connections with significantly less boilerplate code:

// Create a TCP Socket for the client
Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

// Resolve the server address and port
IPAddress serverAddress = IPAddress.Parse("服务器IP");
IPEndPoint serverEndpoint = new IPEndPoint(serverAddress, 服务器端口);

// Connect to the server
sender.Connect(serverEndpoint);

// Send data to the server
byte[] messageBuffer = Encoding.UTF8.GetBytes("data to send");
sender.Send(messageBuffer);

The key distinction between client and server implementations lies in scope: servers must manage multiple concurrent connections through separate Socket instances, while clients typically miantain a single connection to transmit and receive data.

Tags: C#

Related Articles

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.