Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Making Socket Based Application Using TcpListener and TCPClient

0.00/5 (No votes)
10 Jun 2002 1  
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