Step-by-Step Guide: Creating a TCP Server in C#
This guide will walk you through creating a basic TCP server in C#. I’ll explain each step clearly for someone with some programming knowledge.
What is a TCP Server?
A TCP server is a program that listens for incoming connections from clients and can exchange data with them over a network using the TCP protocol (reliable, ordered communication).
Step 1: Set Up Your Project
-
Open Visual Studio (or your preferred C# IDE)
-
Create a new Console Application project
-
Name it “TCPServer” or something similar
Step 2: Add Required Namespace
At the top of your Program.cs file, add:
csharp
Copy
Download
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;These give us access to networking functionality.
Step 3: Create the TCP Listener
In your Main method, add this code:
csharp
Copy
Download
// Define the port you want to use
int port = 8080;
// Create a TcpListener that will listen on any IP address
TcpListener server = new TcpListener(IPAddress.Any, port);-
**port**: Choose a port number (1024-49151 are good for custom apps) -
**IPAddress.Any**: Means the server will listen on all network interfaces
Step 4: Start the Server
Add these lines to start listening:
csharp
Copy
Download
// Start the server
server.Start();
Console.WriteLine("Server started on port " + port);
Console.WriteLine("Waiting for connections...");Step 5: Accept Client Connections
Now we’ll wait for a client to connect:
csharp
Copy
Download
// Accept a client connection (this blocks until a client connects)
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Client connected!");Step 6: Set Up Streams for Communication
We’ll use NetworkStream to send/receive data:
csharp
Copy
Download
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();Step 7: Communicate with the Client
Let’s add simple send/receive logic:
csharp
Copy
Download
// Buffer for reading data
byte[] buffer = new byte[1024];
int bytesRead;
// Loop to receive all the data sent by the client
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
{
// Convert the data to a string and display it
string data = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received: " + data);
// Send back a response
string response = "Server received: " + data;
byte[] msg = Encoding.ASCII.GetBytes(response);
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Sent: " + response);
}Step 8: Clean Up
After communication is done:
csharp
Copy
Download
// Shutdown and close connection
client.Close();
Console.WriteLine("Client disconnected.");Step 9: Complete Example
Here’s the complete code:
csharp
Copy
Download
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class Program
{
static void Main(string[] args)
{
int port = 8080;
// Create TCP listener
TcpListener server = new TcpListener(IPAddress.Any, port);
try
{
// Start the server
server.Start();
Console.WriteLine("Server started on port " + port);
Console.WriteLine("Waiting for connections...");
// Enter the listening loop
while (true)
{
// Accept a client connection
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Client connected!");
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
// Buffer for reading data
byte[] buffer = new byte[1024];
int bytesRead;
// Loop to receive all the data sent by the client
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
{
// Convert the data to a string and display it
string data = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received: " + data);
// Send back a response
string response = "Server received: " + data;
byte[] msg = Encoding.ASCII.GetBytes(response);
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Sent: " + response);
}
// Shutdown and close connection
client.Close();
Console.WriteLine("Client disconnected.");
}
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
// Stop listening for new clients
server.Stop();
}
}
}How to Test Your Server
-
Run this program in Visual Studio
-
Open a command prompt and use telnet to connect:CopyDownload
telnet localhost 8080(If telnet isn’t installed, you can enable it in Windows Features)
-
Type messages in the telnet window - they should appear in your server console
-
The server will echo back each message with “Server received: ” prefix
Important Notes
-
This is a basic single-client server. For multiple clients, you’d need to use threads or async methods.
-
The server will keep running until you stop it (Ctrl+C in console)
-
In a real application, you’d want better error handling and logging
Would you like me to explain any part in more detail or show you how to extend this basic example?
New chat