Click here to Skip to main content
Licence 
First Posted 1 Oct 2001
Views 374,583
Bookmarked 83 times

Introduction to TCP client server in C#

By | 1 Oct 2001 | Article
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 

//
/*   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

About the Author

S.Thangaraju



United States United States

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 4 PinmemberLaxmikant_Yadav1:48 16 Feb '12  
Questionproblem Pinmembermostafa.elsadany16:56 12 Sep '11  
Generalgreetings Pinmembersamathu0:30 25 Feb '11  
GeneralNewer or updated version Pinmemberjotorres4:26 26 Aug '10  
GeneralC# Protocol Builder PinmemberHassan Assalih22:23 18 Aug '10  
GeneralRe: C# Protocol Builder Pinmembersvbrown7:53 19 Jan '11  
GeneralMy vote of 5 Pinmembernaim94a5:06 18 Jul '10  
GeneralTools to build Protocol PinmemberHassan Assalih21:14 14 May '10  
GeneralLovely!!! PinmemberTeenpacker8:57 8 Apr '09  
GeneralRe: Lovely!!! PinmemberM-Dawg11:17 25 Jul '09  
GeneralRe: Lovely!!! Pinmembertomtom198021:39 29 Jul '09  
GeneralRe: Lovely!!! Pinmembershani_n77:18 15 May '10  
GeneralRe: Lovely!!! Pinmemberolekskin6:57 26 Jan '11  
Generalconnection refused if I use local machine's network IP instead of '127.0.0.1' PinmemberAatif Chaudhry0:38 4 Mar '09  
GeneralRe: connection refused if I use local machine's network IP instead of '127.0.0.1' Pinmemberjbo.s22:23 19 Nov '09  
Generalbest simple C# server/client Pinmemberericgoodchild5:48 16 Dec '08  
GeneralWow that was easy Pinmemberjchalfant9:15 20 Nov '08  
GeneralRe: Wow that was easy PinmemberSp3cial15:08 2 Dec '08  
QuestionReceiveTimeOut Pinmemberborbelyr0:52 29 Apr '08  
Generalnamespace 'Net' does not exists Pinmemberrami_84a9:13 29 Feb '08  
GeneralRe: namespace 'Net' does not exists PinmemberDiamonddrake12:28 8 Oct '09  
Generaltransfering file between client and server in C# Pinmembermetal_sheer4:48 15 Mar '06  
QuestionMultiple Connections? PinmemberRikaino21:35 16 Jul '05  
AnswerRe: Multiple Connections? PinmemberMavarok8:57 4 Jun '06  
GeneralHelp needed PinmemberMd Saleem Navalur0:54 29 Mar '05  

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.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120517.1 | Last Updated 2 Oct 2001
Article Copyright 2001 by S.Thangaraju
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid