Click here to Skip to main content
Click here to Skip to main content

Making Socket Based Application Using TcpListener and TCPClient

, 10 Jun 2002
Rate this:
Please Sign up or sign in to vote.
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.

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.

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

Share

About the Author

Faraz Ahmed Siddiqui
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

 
QuestionI NEED HELP TO SEND MULTIPLE FILES FROM FOLDER OF HANDHELD TO SERVER USING THIS SOCKET PinmemberMember 1063809625-May-14 23:16 
QuestionThanks Pinmemberchandr gupt20-Dec-12 22:15 
Questioncode in c# Pinmembermickelthelord1-May-12 13:35 
QuestionHello Sir Pinmemberdonpp4617-Apr-12 20:05 
QuestionThanks for the help PinmemberKenkoJones13-Feb-12 2:50 
RantIs that a joke or you really tried to bring something to the community PinmemberMember 165527524-Sep-10 6:56 
GeneralRe: Is that a joke or you really tried to bring something to the community Pinmembersvbrown19-Jan-11 7:48 
Generalre-inventing the wheel PinmemberProtocol Builder1-Sep-10 21:25 
GeneralRe: re-inventing the wheel PinmemberMikeKosak8-Dec-11 8:03 
GeneralMy vote of 2 PinmemberGuy Baseke23-Nov-09 11:43 
QuestionHow to make it work only with forms? PinmemberJoseSonia5-Jun-09 1:08 
General[Message Deleted] Pinmemberit.ragester2-Apr-09 21:58 
QuestionTcpListener and a C client Pinmemberphyo00917-Sep-05 4:08 
GeneralInfo needed, Client IP PinmemberMd Saleem Navalur29-Mar-05 0:56 
QuestionHow can I send message from server? Pinmemberserunja14-Jan-05 5:42 
Generalusage NON .Net application Pinmemberkrssagar23-Aug-04 14:50 
Generalstop button Pinmemberbahmadi21-Nov-03 7:51 
Generalcombine in 1 Pinmemberhaimon1518-Mar-03 12:32 
GeneralHi, I have read your thread, and....a prb Pinmembersteve_cluj20-Jun-02 19:53 
GeneralRe: Hi, I have read your thread, and....a prb Pinmemberbranco8-Apr-03 11:31 
GeneralRe: Hi, I have read your thread, and....a prb PinsussAnonymous19-Apr-05 8:56 
GeneralRe: Hi, I have read your thread, and....a prb Pinmemberosirisgothra7-Jul-07 19:24 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140827.1 | Last Updated 11 Jun 2002
Article Copyright 2002 by Faraz Ahmed Siddiqui
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid