Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
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.

Total page views :  103841
Total downloads :  2634
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
sampleTcpUdpClientCode.zip
 
Become a Sponsor

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


Login to add your contents and source code to 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.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
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.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
sampleTcpUdpClientCode.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
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 | Delete | 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 | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.