Click here to Skip to main content
6,634,665 members and growing! (15,880 online)
Email Password   helpLost your password?
General Programming » Internet / Network » Client/Server Development     Intermediate

Simple TCP/IP Console Client (TcpClient, MultiThreading)

By Vigrid

This is a tutorial on how to write a very simple TCP/IP console client that asks for a hostname and port which it will connect to. It spawns two threads - sending thread and receiving thread.
C#, Windows, .NET 1.0, Visual Studio, Dev
Posted:21 Apr 2003
Views:94,418
Bookmarked:51 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
12 votes for this article.
Popularity: 3.48 Rating: 3.23 out of 5

1
2 votes, 16.7%
2
1 vote, 8.3%
3
1 vote, 8.3%
4
8 votes, 66.7%
5

Introduction

This is my first tutorial on C# programming. I'm not too familiar with the language yet, so please excuse all my small mistakes. The aim of this tutorial is to show how to write an application that connects to a service, opens a network stream for reading and writing, and allows user to type commands or data line-by-line. It can be useful to explore and learn simple network protocols (such as IRC) for writing future, more advanced clients.

The Idea

  • Connect to server on specified port.
  • Create sending thread.
    • If user enters data - send it to the server.
    • If application still runs - wait for more data to send.
  • 3. Create listening thread.
    • If server sends data to client - display or process it.
    • If application still runs - wait for more incoming data.

That's how a simple chat-client could look like. User should have at all times the possibility to enter his commands or messages, while application would process all incoming data (for an example - it should display messages on the screen). That requires two independent threads, one "interface" thread, responsible for user input, and second thread which will deal with incoming messages.

The Code

Nothing more to say here.

  
using System;
using System.Text;
using System.Net.Sockets;
using System.Threading;
 
namespace SimpleTCPClient
{
    class cApplication
    {
        /* NetworkStream that will be used */
        private static NetworkStream    myStream;
        /* TcpClient that will connect for us */
        private static TcpClient        myClient;
        /* Storage space */
        private static byte[]            myBuffer;
        /* Application running flag */
        private static bool                bActive = true;
 
        /* Thread responsible for "remote input" */
        private static void ListenThread()
        {
            Console.WriteLine("Listening...");
            while(bActive)
            {
                /* Reading data from socket (stores the length of data) */
                int lData = myStream.Read(myBuffer, 0, 
                      myClient.ReceiveBufferSize);
                /* String conversion (to be displayed on console) */
                String myString = Encoding.ASCII.GetString(myBuffer);
                /* Trimming data to needed length, 
                   because TcpClient buffer is 8kb long */
                /* and we don't need that load of data 
                   to be displayed at all times */
                /* (this could be done better for sure) */
                myString = myString.Substring(0, lData);
                /* Display message */
                Console.Write(myString);
            }
        }
 
        /* Thread responsible for "local input" */
        private static void SendThread()
        {
            Console.WriteLine("Sending...");
            while(bActive)
            {
                /* Simple prompt */
                Console.Write("> ");
                /* Reading message/command from console */
                String myString = Console.ReadLine() + "\n";
                /* Sending the data */
                myStream.Write(Encoding.ASCII.GetBytes(
                     myString.ToCharArray()), 0, myString.Length);
            }
        }
 
        /* Entry point */
        static void Main(string[] args)
        {
            Console.Write("Enter server name/address: ");
            String strServer = Console.ReadLine();
 
            Console.Write("Enter remote port: ");
            String strPort = Console.ReadLine();
 
            /* Connecting to server (will crash if address/name is incorrect) */
            myClient = new TcpClient(strServer, Int32.Parse(strPort));
            Console.WriteLine("Connected...");
            /* Store the NetworkStream */
            myStream = myClient.GetStream();
            /* Create data buffer */
            myBuffer = new byte[myClient.ReceiveBufferSize];
 
            /* Vital: Create listening thread and assign it to ListenThread() */
            Thread tidListen = new Thread(new ThreadStart(ListenThread));
            /* Vital: Create sending thread and assign it to SendThread() */
            Thread tidSend = new Thread(new ThreadStart(SendThread));
 
            Console.WriteLine("Application connected and ready...");
            Console.WriteLine("----------------------------------");
 
            /* Start listening thread */
            tidListen.Start();
            /* Start sending thread */
            tidSend.Start();
        }
    }
}
 

The End

It's quite easy to use sockets in C#. The above code lacks exception handling routines and a beautiful interface, but it should give an idea of how to code simple client applications. Maybe in the next tutorial I will write about creating a listening server application and a simple chat client.

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

Vigrid


Member

Occupation: Software Developer
Location: Poland Poland

Other popular Internet / Network articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 10 of 10 (Total in Forum: 10) (Refresh)FirstPrevNext
GeneralBlocked thread... PinmemberWill Willow2:11 6 Apr '05  
GeneralRe: Blocked thread... PinmemberVigrid11:28 6 Apr '05  
GeneralRe: Blocked thread... Pinmembermiamuy3:29 14 Jan '07  
GeneralInfo needed,, Client IP PinmemberMd Saleem Navalur1:55 29 Mar '05  
GeneralRe: Info needed,, Client IP PinmemberVigrid2:28 29 Mar '05  
GeneralIsn't it dangerous? PinmemberRickard Andersson1821:09 22 Apr '03  
GeneralRe: Isn't it dangerous? PinmemberVigrid22:53 22 Apr '03  
GeneralRe: Isn't it dangerous? PinmemberMadaha8:33 11 Dec '03  
GeneralRe: Isn't it dangerous? PinmemberVigrid12:07 11 Dec '03  
GeneralRe: Isn't it dangerous? PinmemberCodebender8:04 11 Jun '04  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 21 Apr 2003
Editor: Nishant Sivakumar
Copyright 2003 by Vigrid
Everything else Copyright © CodeProject, 1999-2009
Web18 | Advertise on the Code Project