Click here to Skip to main content
15,500,453 members
Articles / Programming Languages / C#
Posted 10 Jun 2002


57 bookmarked

Making Socket Based Application Using TcpListener and TCPClient

Rate me:
Please Sign up or sign in to vote.
3.05/5 (19 votes)
10 Jun 20022 min read
Teaches how to program a socket based application in VC#.


In order to do communication between two applications in client/server environment, we need some type of addressing, and mechanism or protocol to do proper communication. Communication can be done in two ways:

  • Connection Oriented

    In connection oriented service, we establish a proper connection between client and server through some sort of handshaking. For this, we have a protocol or standard called TCP. I.e., TCP provides us service to send data in connection oriented environment.

  • Connection Less

    In connection less service, we do data transfer without any connection between client and server. For this, we have a protocol or standard called UDP. I.e., UDP provides us service to send data without taking care of client activation.

Both ways have there advantages and disadvantages and can be used according to the type of application. Like, TCP provides reliable and secure transfer of data but slow, while UDP provides unreliable transfer of data but fast.

Now, to implement the above protocols, we require some sort of end points which are provided by Sockets. As you know, we have lots of ports available in computer to do end to end communication, and Sockets work on these ports.

.NET framework provides us a higher level of abstraction upon sockets in the form of TcpListener, TCPClient and UDPClient. TcpListener is a high level interface for server application and TCPClient is for client application. They are both implemented over sockets but provide easier and high level interface. To do end to end communication between TcpListener and TCPClient without any complications, .NET provides NetworkStream. We can use both stream reader and writer over NetworkStream through StreamReader and StreamWriter.

Here, I’ll show you a simple client/server application which performs simple messaging using TcpListener, TCPClient and NetworkStream, StreamReader and StreamWriter.

Here is the code:

TCP Server

This is the server side code which listens on a particular port using TcpListener.

using System;
using System.Windows.Forms;
using System.Net.Sockets;
using System.IO;
namespace TCPSocketServer
/// Summary description for TCPSockServer.
public class Server : Form

///Variables & Properties
Button btnStartServer;
private StreamWriter serverStreamWriter;
private StreamReader serverStreamReader;

public Server()
//create StartServer button set its properties & event handlers 
this.btnStartServer = new Button();
this.btnStartServer.Text = "Start Server";
this.btnStartServer.Click += new System.EventHandler(this.btnStartServer_Click);
//add controls to form
///Main Method
public static void Main(string[] args)
//creat n display windows form
Server tcpSockServer = new Server();
///Start Server
private bool StartServer()
//create server's tcp listener for incoming connection
TcpListener tcpServerListener = new TcpListener(4444);
tcpServerListener.Start(); //start server
Console.WriteLine("Server Started");
this.btnStartServer.Enabled = false;
//block tcplistener to accept incoming connection
Socket serverSocket = tcpServerListener.AcceptSocket();

if (serverSocket.Connected)
Console.WriteLine("Client connected");
//open network stream on accepted socket
NetworkStream serverSockStream = new NetworkStream(serverSocket);
serverStreamWriter = new StreamWriter
serverStreamReader = new StreamReader(serverSockStream);
catch(Exception e)
return false;

return true;
} ////////////////////////////////////////////////////
///Event handlers
private void btnStartServer_Click(object sender,System.EventArgs e)

//start server
if (!StartServer())
Console.WriteLine("Unable to start server");

//sending n receiving msgs
while (true)
("CLIENT: "+serverStreamReader.ReadLine()); 

TCP Client

This is the client side code which connects to the server through a particular port on which the server is listening client’s request, using TCPClient.

using System;
using System.Windows.Forms;
using System.Net.Sockets;
using System.IO;

namespace TCPSocketClient
/// Summary description for Client.
public class Client : Form

///Variables & Properties

private Button btnConnectToServer;
private Button btnSendMessage;
private StreamReader clientStreamReader;
private StreamWriter clientStreamWriter;

public Client()
//create ConnectToServer button, set its properties & event handlers
this.btnConnectToServer = new Button();
this.btnConnectToServer.Text = "Connect";
this.btnConnectToServer.Click += 
  new System.EventHandler(btnConnectToServer_Click); 
//create SendMessage button, set its properties & event handlers
this.btnSendMessage = new Button();
this.btnSendMessage.Text = "Send Message";
this.btnSendMessage.Top += 30;
this.btnSendMessage.Width += 20;
this.btnSendMessage.Click += new System.EventHandler(btnSendMessage_Click); 
//add controls to windows form

///Main method
public static void Main(string[] args)
//create n display windows form
Client tcpSockClient = new Client();
///Connect to server
private bool ConnectToServer()
//connect to server at given port
TcpClient tcpClient = new TcpClient("localhost",4444); 
Console.WriteLine("Connected to Server");
//get a network stream from server
NetworkStream clientSockStream = tcpClient.GetStream();
clientStreamReader = new StreamReader(clientSockStream);
clientStreamWriter = new StreamWriter(clientSockStream);
catch(Exception e)
return false;
return true;
///Event Handlers
private void btnConnectToServer_Click(object sender,System.EventArgs e)
//connect to server
if (!ConnectToServer())
Console.WriteLine("Unable to connect to server");
private void btnSendMessage_Click(object sender,System.EventArgs e)
//send message to server
Console.WriteLine("SERVER: "+clientStreamReader.ReadLine());
catch(Exception se)


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Written By
Web Developer
United Kingdom United Kingdom
Faraz Ahmed is a software engineer at Kalsoft (Pvt) Limited, karahci Pakistan and worked on Microsoft technologies mainly on VC++,COM,VB and now working on VC#.

Comments and Discussions

QuestionNice Article Pin
Rahul VB18-Oct-16 2:43
professionalRahul VB18-Oct-16 2:43 
This is a very nice article. Thumbs Up | :thumbsup:

But, it would be also helpful if you compare the tcp class and the normal socket class.
What i want to say is that: why should one use tcpListner and tcpClient and not normal socket ? If you could elaborate it more nicely would be great.

For example : As you said tcp classes provide a layer of abstraction, but writing a wrapper can also have their advantages and disadvantages.

This was just a suggestion. Smile | :)

Thanks again for writting this article.
Member 1063809626-May-14 0:16
MemberMember 1063809626-May-14 0:16 
QuestionThanks Pin
dattaram_garud20-Dec-12 23:15
Memberdattaram_garud20-Dec-12 23:15 
Questioncode in c# Pin
mickelthelord1-May-12 14:35
Membermickelthelord1-May-12 14:35 
QuestionHello Sir Pin
donpp4617-Apr-12 21:05
Memberdonpp4617-Apr-12 21:05 
QuestionThanks for the help Pin
KenkoJones13-Feb-12 3:50
MemberKenkoJones13-Feb-12 3:50 
RantIs that a joke or you really tried to bring something to the community Pin
Member 165527524-Sep-10 7:56
MemberMember 165527524-Sep-10 7:56 
GeneralRe: Is that a joke or you really tried to bring something to the community Pin
svbrown19-Jan-11 8:48
Membersvbrown19-Jan-11 8:48 
Generalre-inventing the wheel Pin
Protocol Builder1-Sep-10 22:25
MemberProtocol Builder1-Sep-10 22:25 
GeneralRe: re-inventing the wheel Pin
MikeKosak8-Dec-11 9:03
MemberMikeKosak8-Dec-11 9:03 
GeneralMy vote of 2 Pin
Guy Baseke23-Nov-09 12:43
MemberGuy Baseke23-Nov-09 12:43 
QuestionHow to make it work only with forms? Pin
JoseSonia5-Jun-09 2:08
MemberJoseSonia5-Jun-09 2:08 
General[Message Deleted] Pin
it.ragester2-Apr-09 22:58
Memberit.ragester2-Apr-09 22:58 
QuestionTcpListener and a C client Pin
phyo00917-Sep-05 5:08
Memberphyo00917-Sep-05 5:08 
GeneralInfo needed, Client IP Pin
Md Saleem Navalur29-Mar-05 1:56
MemberMd Saleem Navalur29-Mar-05 1:56 
GeneralRe: Info needed, Client IP Pin
Rahul VB18-Oct-16 2:38
professionalRahul VB18-Oct-16 2:38 
QuestionHow can I send message from server? Pin
serunja14-Jan-05 6:42
Memberserunja14-Jan-05 6:42 
Generalusage NON .Net application Pin
krssagar23-Aug-04 15:50
Memberkrssagar23-Aug-04 15:50 
Generalstop button Pin
bahmadi21-Nov-03 8:51
Memberbahmadi21-Nov-03 8:51 
Generalcombine in 1 Pin
haimon1518-Mar-03 13:32
Memberhaimon1518-Mar-03 13:32 
GeneralHi, I have read your thread, and....a prb Pin
steve_cluj20-Jun-02 20:53
Membersteve_cluj20-Jun-02 20:53 
GeneralRe: Hi, I have read your thread, and....a prb Pin
branco8-Apr-03 12:31
Memberbranco8-Apr-03 12:31 
GeneralRe: Hi, I have read your thread, and....a prb Pin
Anonymous19-Apr-05 9:56
MemberAnonymous19-Apr-05 9:56 
GeneralRe: Hi, I have read your thread, and....a prb Pin
osirisgothra7-Jul-07 20:24
Memberosirisgothra7-Jul-07 20:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.