Blue Theme Orange Theme Green Theme Red Theme
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Mindcracker MVP Summit 2012
Search :       Advanced Search »
Home » Networking » A Simple Multi-threaded TCP/UDP Server and Client V2.

A Simple Multi-threaded TCP/UDP Server and Client V2.

This is the second version of my client/server program. The server and the client can be run on the same machine or on different machines. The following is the brief description of the server and the client programs specifically.

Page Views : 182164
Downloads : 4702
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
sampleTcpUdpClientCode.zip
 
 
Team Foundation Server Hosting
Become a Sponsor
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Description 

This is the second version of my client/server program.  The server and the client can be run on the same machine or on different machines.  The following is the brief description of the server and the client programs specifically.

sampleTcpUdpServer2.cs:  This program functions exactly the same as v1 posted earlier.  The only difference is in the coding.  It employs a more efficient coding way for the socket programming.  It uses the TcpListener class provided by the .Net class library, instead of the traditional (bind/listen/accept) way employed in v1.

Usage : sampleTcpUdpServer2

sampleTcpUdpClient2.cs:  Similar to te changes made to the server program, this client program employs a more efficient way of socket programming provided by the .Net class library.  It uses TcpClient and UdpClient classes instead of the traditional way employed in v1.

Usage : sampleTcpUdpClient2 <TCP or UDP> <destination hostname or IP> "Any message."

Example: sampleTcpUdpClient2 TCP your_hostname "hello. how are you?"

All the other information is provided at the beginning of each file. 







Source Code:

/* Project : Simple Multi-threaded TCP/UDP Server v2
* Author : Patrick Lam
* Date : 09/19/2001
* Brief : The simple multi-threaded TCP/UDP Server v2 does the same thing as v1. What
* it intends to demonstrate is the amount of code you can save by using
TcpListener
* instead of the traditional raw socket implementation (The UDP part is still
* the same. When you compare the following code with v1, you will see the
* difference.
* Usage : sampleTcpUdpServer2
*/

namespace sampleTcpUdpServer2
{
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public class SampleTcpUdpServer2
{
private const int sampleTcpPort = 4567;
private const int sampleUdpPort = 4568;
public Thread sampleTcpThread, sampleUdpThread;
public SampleTcpUdpServer2()
{
try
{
//Starting the TCP Listener thread.
sampleTcpThread = new Thread(new ThreadStart(StartListen2));
sampleTcpThread.Start();
Console.WriteLine("Started SampleTcpUdpServer's TCP Listener Thread!\n");
}
catch (Exception e)
{
Console.WriteLine("An TCP Exception has occurred!" + e.ToString());
sampleTcpThread.Abort();
}
try
{
//Starting the UDP Server thread.
sampleUdpThread = new Thread(new ThreadStart(StartReceiveFrom2));
sampleUdpThread.Start();
Console.WriteLine("Started SampleTcpUdpServer's UDP Receiver Thread!\n");
}
catch (Exception e)
{
Console.WriteLine("An UDP Exception has occurred!" + e.ToString());
sampleUdpThread.Abort();
}
}
public static void Main(String[] argv)
{
SampleTcpUdpServer2 sts =
new SampleTcpUdpServer2();
}
public void StartListen2()
{
//Create an instance of TcpListener to listen for TCP connection.
TcpListener tcpListener = new TcpListener(sampleTcpPort);
try
{
while (true)
{
tcpListener.Start();
//Program blocks on Accept() until a client connects.
Socket soTcp = tcpListener.AcceptSocket();
Console.WriteLine("SampleClient is connected through TCP.");
Byte[] received =
new Byte[512];
int bytesReceived = soTcp.Receive(received, received.Length, 0);
String dataReceived = System.Text.Encoding.ASCII.GetString(received);
Console.WriteLine(dataReceived);
String returningString = "The Server got your message through TCP: " +
dataReceived;
Byte[] returningByte = System.Text.Encoding.ASCII.GetBytes
(returningString.ToCharArray());
//Returning a confirmation string back to the client.
soTcp.Send(returningByte, returningByte.Length, 0);
tcpListener.Stop();
}
}
catch (SocketException se)
{
Console.WriteLine("A Socket Exception has occurred!" + se.ToString());
}
}
public void StartReceiveFrom2()
{
IPHostEntry localHostEntry;
try
{
//Create a UDP socket.
Socket soUdp = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
try
{
localHostEntry = Dns.GetHostByName(Dns.GetHostName());
}
catch(Exception)
{
Console.WriteLine("Local Host not found");
// fail
return ;
}
IPEndPoint localIpEndPoint =
new IPEndPoint(localHostEntry.AddressList[0], sampleUdpPort);
soUdp.Bind(localIpEndPoint);
while (true)
{
Byte[] received =
new Byte[256];
IPEndPoint tmpIpEndPoint =
new IPEndPoint(localHostEntry.AddressList[0], sampleUdpPort);
EndPoint remoteEP = (tmpIpEndPoint);
int bytesReceived = soUdp.ReceiveFrom(received, ref remoteEP);
String dataReceived = System.Text.Encoding.ASCII.GetString(received);
Console.WriteLine("SampleClient is connected through UDP.");
Console.WriteLine(dataReceived);
String returningString = "The Server got your message through UDP:" + dataReceived;
Byte[] returningByte = System.Text.Encoding.ASCII.GetBytes(returningString.ToCharArray());
soUdp.SendTo(returningByte, remoteEP);
}
}
catch (SocketException se)
{
Console.WriteLine("A Socket Exception has occurred!" + se.ToString());
}
}
}
}
/* Project: Simple TCP/UDP Client v2
* Author : Patrick Lam
* Date : 09/19/2001
* Brief : The simple TCP/UDP Client v2 does exactly the same thing as v1. What
itintends
* to demonstrate is the amount of code you can save by using TcpClient and UdpClient
* instead of the traditional raw socket implementation. When you
* compare the following code with v1, you will see the difference.
* Usage : sampleTcpUdpClient2 <TCP or UDP> <destination hostname or IP> "Any message."
* Example: sampleTcpUdpClient2 TCP localhost "hello. how are you?"
* Bugs : When you send a message with UDP, you can't specify localhost as the
* destination. Doing so will produce an exception. Can't figure out why yet. The workaround
* to use the machine's hostname instead.
*/

namespace multiThreadedTcpUdpClient2
{
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public class sampleTcpUdpClient2
{
public enum clientType {TCP, UDP}; //Type of connection the client is making.
private const int ANYPORT = 0;
private const int SAMPLETCPPORT = 4567;
private const int SAMPLEUDPPORT = 4568;
private bool readData = false;
public clientType cliType;
private bool DONE = false;
public sampleTcpUdpClient2(clientType CliType)
{
this.cliType = CliType;
}
public void sampleTcpClient2(String serverName, String whatEver)
{
try
{
//Create an instance of TcpClient.
TcpClient tcpClient = new TcpClient(serverName,SAMPLETCPPORT);
//Create a NetworkStream for this tcpClient instance.
//This is only required for TCP stream.
NetworkStream tcpStream = tcpClient.GetStream();
if (tcpStream.CanWrite)
{
Byte[] inputToBeSent = System.Text.Encoding.ASCII.GetBytes(whatEver.ToCharArray());
tcpStream.Write(inputToBeSent, 0, inputToBeSent.Length);
tcpStream.Flush();
}
while (tcpStream.CanRead && !DONE)
{
//We need the DONE condition here because there is possibility that
//the stream is ready to be read while there is nothing to be read.
if (tcpStream.DataAvailable)
{
Byte[] received =
new Byte[512];
int nBytesReceived = tcpStream.Read(received, 0, received.Length);
String dataReceived = System.Text.Encoding.ASCII.GetString(received);
Console.WriteLine(dataReceived);
DONE =
true;
}
}
}
catch (Exception e)
{
Console.WriteLine("An Exception has occurred.");
Console.WriteLine(e.ToString());
}
}
public void sampleUdpClient2(String serverName, String whatEver)
{
try
{
//Create an instance of UdpClient.
UdpClient udpClient = new UdpClient(serverName, SAMPLEUDPPORT);
Byte[] inputToBeSent =
new Byte[256];
inputToBeSent = System.Text.Encoding.ASCII.GetBytes(whatEver.ToCharArray());
IPHostEntry remoteHostEntry = Dns.GetHostByName(serverName);
IPEndPoint remoteIpEndPoint =
new IPEndPoint(remoteHostEntry.AddressList[0], SAMPLEUDPPORT);
int nBytesSent = udpClient.Send(inputToBeSent, inputToBeSent.Length);
Byte[] received =
new Byte[512];
received = udpClient.Receive(
ref remoteIpEndPoint);
String dataReceived = System.Text.Encoding.ASCII.GetString(received);
Console.WriteLine(dataReceived);
udpClient.Close();
}
catch (Exception e)
{
Console.WriteLine("An Exception Occurred!");
Console.WriteLine(e.ToString());
}
}
public static void Main(String[] argv)
{
if (argv.Length < 3)
{
Console.WriteLine("Usage: sampleTcpUdpClient2 <TCP or UDP> <Server Name or IP Address> Message");
Console.WriteLine("Example: sampleTcpUdpClient2 TCP localhost ''hello. how are you?''");
}
else if ((argv[0] == "TCP") || (argv[0] == "tcp"))
{
sampleTcpUdpClient2 stc =
new sampleTcpUdpClient2(clientType.TCP);
stc.sampleTcpClient2(argv[1], argv[2]);
Console.WriteLine("The TCP server is disconnected.");
}
else if ((argv[0] == "UDP") || (argv[0] == "udp"))
{
sampleTcpUdpClient2 suc =
new sampleTcpUdpClient2(clientType.UDP);
suc.sampleUdpClient2(argv[1], argv[2]);
Console.WriteLine("The UDP server is disconnected.");
}
}
}
}
// created on 8/26/2001 at 1:21 PM

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Patrick Lam
I am a C/C++ programmer in the telecom field for about 6 years.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
Question for you by Chris On March 29, 2007
Hello, Thank you for your post. That code is working fine from my computer to another computer on my LAN. Question: I also have connected via VPN to a remote machine, using their given username and password. Next, they have given me an IP Address and Port, so that I can connect to their TCP/IP Socket. For some reason, the Client here does not connect to their socket via VPN. Do you have any suggestions how I can connect to their socket? Many thanks, Chris (send8w@aol.com)
Reply | Email | Modify 
a question by ayse On December 11, 2009
hi,
i tried to run client server codes. But i can't run client code via prompt commant. Could you explain step by step how to run sampleTcpUdpClient2 code?
thanks...
Reply | Email | Modify 
aboart TcpListener by Nick On May 8, 2010
The Problem that what if you need to abort the listener or wants to keep the connection alive with the clients, I found the tool in www.protocol-builder.com which solves this problems, but it has to UDP support yet !!
Reply | Email | Modify 
Stopping threads? by Ray On August 24, 2010
Great code!  However, how do you go about killing the TCP and UDP server threads when the program ends?
Reply | Email | Modify 
Mindcracker MVP Summit 2012
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.