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

Introduction to TCP client server in C#

Rate me:
Please Sign up or sign in to vote.
4.73/5 (76 votes)
1 Oct 2001 1.2M   30.2K   155   72
An article on TCP client server programming

Introduction

This is a simple implementation of a TCP client server relationship.

To use

Compile the server and client programs separately. Before compiling change the IP address in both programs to match that of your machine (NOTE : to get your IP address  run 'ipconfig' from the command prompt in Windows NT/2000 m/c's)

When the server program is run, it will indicate at which IP it is running and the port it is listening to. Now run the client program is run , so as to establish a connection with the server.

When a connection is established the server will display the IP address and Port from where it has accepted the connection and client will ask for the string which is to be transmitted to the server.

The server on reciept of the string will display it, send an acknowledgement which will be recieved by the client.

The client can be either run from the same machine as the server or from a different machine. If run from a different machine then a network connection should exist between the machines running the server and client programs 

C#
//
/*   Server Program    */
                 
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;

public class serv {
    public static void Main() {
    try {
        IPAddress ipAd = IPAddress.Parse("172.21.5.99");
         // use local m/c IP address, and 
         // use the same in the client

/* Initializes the Listener */
        TcpListener myList=new TcpListener(ipAd,8001);

/* Start Listeneting at the specified port */        
        myList.Start();
        
        Console.WriteLine("The server is running at port 8001...");    
        Console.WriteLine("The local End point is  :" + 
                          myList.LocalEndpoint );
        Console.WriteLine("Waiting for a connection.....");
        
        Socket s=myList.AcceptSocket();
        Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
        
        byte[] b=new byte[100];
        int k=s.Receive(b);
        Console.WriteLine("Recieved...");
        for (int i=0;i<k;i++)
            Console.Write(Convert.ToChar(b[i]));

        ASCIIEncoding asen=new ASCIIEncoding();
        s.Send(asen.GetBytes("The string was recieved by the server."));
        Console.WriteLine("\nSent Acknowledgement");
/* clean up */            
        s.Close();
        myList.Stop();
            
    }
    catch (Exception e) {
        Console.WriteLine("Error..... " + e.StackTrace);
    }    
    }
    
}

---------------------------------------------------------------------------

/*       Client Program      */

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;


public class clnt {

    public static void Main() {
        
        try {
            TcpClient tcpclnt = new TcpClient();
            Console.WriteLine("Connecting.....");
            
            tcpclnt.Connect("172.21.5.99",8001);
            // use the ipaddress as in the server program
            
            Console.WriteLine("Connected");
            Console.Write("Enter the string to be transmitted : ");
            
            String str=Console.ReadLine();
            Stream stm = tcpclnt.GetStream();
                        
            ASCIIEncoding asen= new ASCIIEncoding();
            byte[] ba=asen.GetBytes(str);
            Console.WriteLine("Transmitting.....");
            
            stm.Write(ba,0,ba.Length);
            
            byte[] bb=new byte[100];
            int k=stm.Read(bb,0,100);
            
            for (int i=0;i<k;i++)
                Console.Write(Convert.ToChar(bb[i]));
            
            tcpclnt.Close();
        }
        
        catch (Exception e) {
            Console.WriteLine("Error..... " + e.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
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralRe : Help needed Pin
Anonymous4-Apr-05 9:08
Anonymous4-Apr-05 9:08 
GeneralRe: Help needed Pin
Anon E Moss10-Jun-05 11:43
sussAnon E Moss10-Jun-05 11:43 
GeneralPort 443 Pin
Dominic George30-Nov-03 15:49
Dominic George30-Nov-03 15:49 
GeneralRe: Port 443 Pin
Hossam Abbas17-Aug-04 14:23
Hossam Abbas17-Aug-04 14:23 
GeneralRe: Port 443 Pin
OsoreWatashi21-Apr-09 10:53
OsoreWatashi21-Apr-09 10:53 
GeneralError Pin
jaavaaguru7-Jun-02 23:16
jaavaaguru7-Jun-02 23:16 
GeneralRe: Error Pin
innocence183-Apr-06 20:04
innocence183-Apr-06 20:04 
GeneralProblem with HTTPS and WebRequest Pin
josephgigi18-May-02 11:52
josephgigi18-May-02 11:52 
I am having some problems in accessing a secure site using WebRequest. Class. Hope you could help me.

I have the following URL
https://pacer.train.uscourts.gov/bc/cgi-bin/ChkPasswd.pl?loginid=tr0000&passwd=train&newloc=/bc/cgi-bin/reports.pl

When I paste this URL in IE ,it takes me to the correct page. But when I issue this URL from my C# application, it does not give me the correct page. I get a wrong log in again page as the result..

I am behind a firewall (ISA) and after taking a look at the firewall log, it looks like the user_agent is missing when the SSL tunnel is created when the URL is submitted from the application. (Portion of the log file, iSALog.txt is also attached.). Could the missing UserAgent be the problem since it is the only apparent difference in the log file. If Yes, how can I make it work. Pls note that I am setting the useragent property in my app.

I am attaching the following source code that I am working with. Pls Extract the zip file and Open the WebNavigator.sln under WebNavigator directory. This .sln contains 3 projects
1. WebNavigator: This is a DLL which takes any URL and submits it and return the resulting web page as a string
2. WebNavigatorClient. This exe is the sample client for the above dll
3. ConsoleApplication2. This contains the functionality of the both of the above in one class with a little more encoding etc. This is a MS example slightly modified by me.

If you did not recv an attachement along with this help request, you may download both ISAlog.txt and the zip files from
http://65.187.38.233/images/testsource/

I really appreciate your help and thanks in advance.

Regards
-G Joseph

Generalipconfig Pin
Mazdak1-Apr-02 21:06
Mazdak1-Apr-02 21:06 
GeneralRe: ipconfig Pin
Rickard Andersson203-Apr-02 8:13
Rickard Andersson203-Apr-02 8:13 
GeneralRe: ipconfig Pin
Mazdak3-Apr-02 10:01
Mazdak3-Apr-02 10:01 
GeneralRe: ipconfig Pin
Paul A. Howes3-Apr-02 8:30
Paul A. Howes3-Apr-02 8:30 
GeneralRe: ipconfig Pin
Mazdak3-Apr-02 9:59
Mazdak3-Apr-02 9:59 
GeneralRe: ipconfig Pin
papi8-Aug-02 21:47
papi8-Aug-02 21:47 
GeneralRe: ipconfig Pin
Anonymous21-Jul-04 17:58
Anonymous21-Jul-04 17:58 

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.