Click here to Skip to main content
15,867,686 members
Articles / Programming Languages / C#
Article

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 219.8K   4.3K   57   24
Teaches how to program a socket based application in VC#.

Introduction

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.

C#
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;

//////////////////////////////////////////////////////
///constructor
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
this.Controls.Add(this.btnStartServer);
}
//////////////////////////////////////////////////////
///Main Method
public static void Main(string[] args)
{
//creat n display windows form
Server tcpSockServer = new Server();
Application.Run(tcpSockServer); 
}
//////////////////////////////////////////////////////
///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();

try
{
if (serverSocket.Connected)
{
Console.WriteLine("Client connected");
//open network stream on accepted socket
NetworkStream serverSockStream = new NetworkStream(serverSocket);
serverStreamWriter = new StreamWriter
(serverSockStream);
serverStreamReader = new StreamReader(serverSockStream);
}
}
catch(Exception e)
{
Console.WriteLine(e.StackTrace); 
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)
{
Console.WriteLine
("CLIENT: "+serverStreamReader.ReadLine()); 
serverStreamWriter.WriteLine("Hi!"); 
serverStreamWriter.Flush();
}//while
}
}
}

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.

C#
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;

/////////////////////////////////////////////////////////////////////////////
///Constructor
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
this.Controls.Add(this.btnConnectToServer);
this.Controls.Add(this.btnSendMessage);
}

/////////////////////////////////////////////////////////////////////////////
///Main method
public static void Main(string[] args)
{
//create n display windows form
Client tcpSockClient = new Client();
Application.Run(tcpSockClient);
}
/////////////////////////////////////////////////////////////////////////////
///Connect to server
private bool ConnectToServer()
{
//connect to server at given port
try
{
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)
{
Console.WriteLine(e.StackTrace);
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)
{
try
{
//send message to server
clientStreamWriter.WriteLine("Hello!");
clientStreamWriter.Flush();
Console.WriteLine("SERVER: "+clientStreamReader.ReadLine());
}
catch(Exception se)
{
Console.WriteLine(se.StackTrace);
}
}
}
}

License

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 1:43
professionalRahul VB18-Oct-16 1:43 
QuestionI NEED HELP TO SEND MULTIPLE FILES FROM FOLDER OF HANDHELD TO SERVER USING THIS SOCKET Pin
Member 1063809625-May-14 23:16
Member 1063809625-May-14 23:16 
QuestionThanks Pin
dattaram_garud20-Dec-12 22:15
dattaram_garud20-Dec-12 22:15 
Questioncode in c# Pin
mickelthelord1-May-12 13:35
mickelthelord1-May-12 13:35 
QuestionHello Sir Pin
donpp4617-Apr-12 20:05
donpp4617-Apr-12 20:05 
QuestionThanks for the help Pin
KenkoJones13-Feb-12 2:50
KenkoJones13-Feb-12 2:50 
RantIs that a joke or you really tried to bring something to the community Pin
Member 165527524-Sep-10 6:56
Member 165527524-Sep-10 6:56 
GeneralRe: Is that a joke or you really tried to bring something to the community Pin
svbrown19-Jan-11 7:48
svbrown19-Jan-11 7:48 
Give the guy a break - He made an effort!
Generalre-inventing the wheel Pin
Protocol Builder1-Sep-10 21:25
Protocol Builder1-Sep-10 21:25 
GeneralRe: re-inventing the wheel Pin
MikeKosak8-Dec-11 8:03
MikeKosak8-Dec-11 8:03 
GeneralMy vote of 2 Pin
Guy Baseke23-Nov-09 11:43
Guy Baseke23-Nov-09 11:43 
QuestionHow to make it work only with forms? Pin
JoseSonia5-Jun-09 1:08
JoseSonia5-Jun-09 1:08 
General[Message Deleted] Pin
it.ragester2-Apr-09 21:58
it.ragester2-Apr-09 21:58 
QuestionTcpListener and a C client Pin
phyo00917-Sep-05 4:08
phyo00917-Sep-05 4:08 
GeneralInfo needed, Client IP Pin
Md Saleem Navalur29-Mar-05 0:56
Md Saleem Navalur29-Mar-05 0:56 
GeneralRe: Info needed, Client IP Pin
Rahul VB18-Oct-16 1:38
professionalRahul VB18-Oct-16 1:38 
QuestionHow can I send message from server? Pin
serunja14-Jan-05 5:42
serunja14-Jan-05 5:42 
Generalusage NON .Net application Pin
krssagar23-Aug-04 14:50
krssagar23-Aug-04 14:50 
Generalstop button Pin
bahmadi21-Nov-03 7:51
bahmadi21-Nov-03 7:51 
Generalcombine in 1 Pin
haimon1518-Mar-03 12:32
haimon1518-Mar-03 12:32 
GeneralHi, I have read your thread, and....a prb Pin
steve_cluj20-Jun-02 19:53
steve_cluj20-Jun-02 19:53 
GeneralRe: Hi, I have read your thread, and....a prb Pin
branco8-Apr-03 11:31
branco8-Apr-03 11:31 
GeneralRe: Hi, I have read your thread, and....a prb Pin
Anonymous19-Apr-05 8:56
Anonymous19-Apr-05 8:56 
GeneralRe: Hi, I have read your thread, and....a prb Pin
osirisgothra7-Jul-07 19:24
osirisgothra7-Jul-07 19: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.