Implementing Network Communication with Sockets in C Sharp
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.