Library tutorials & articles
Socket Programming in C# - Part 1
Introduction
The purpose of this article is to show you how you can do socket programming in C#. This article assumes some familiarity with the socket programming, though you need not to be expert in socket programming. There are several flavors to socket programming - like client side , server side , blocking or synchronous , non-blocking or asynchronous etc. With all these flavors in mind , I have decided to break this subject into two parts. In the part 1 I will start with the client side blocking socket. Later on in the second part I will show you how to create server side and non-blocking.
Network programming in windows is possible with sockets. A socket is like a handle to a file. Socket programming resembles the file IO as does the Serial Communication. You can use sockets programming to have two applications communicate with each other. The application are typically on the different computers but they can be on same computer. For the two applications to talk to each either on the same or different computers using sockets one application is generally a server that keeps listening to the incoming requests and the other application acts as a client and makes the connection to the server application. The server application can either accept or reject the connection. If the server accepts the connection, a dialog can begin with between the client and the server. Once the client is done with whatever it needs to do it can close the connection with the server. Connections are expensive in the sense that servers allow finite connections to occur. During the time client has an active connection it can send the data to the server and/or receive the data.
The complexity begins here. When either side (client or server) sends data the other side is supposed to read the data. But how will the other side know when data has arrived. There are two options - either the application needs to poll for the data at regular intervals or there needs to be some sort of mechanism that would enable application to get notifications and application can read the data at that time. Well , after all Windows is an event driven system and the notification system seems an obvious and best choice and it in fact is.
As I said the two applications that need to communicate with each other need to make a connection first. In order for the two application to make connections the two applications need to identify each other ( or each other's computer ). Computers on network have a unique identifier called I.P. address which is represented in dot-notation like 10.20.120.127 etc. Lets see how all this works in .NET.
Related articles
Related discussion
-
C# video Editing/rendering
by pkuchaliya (0 replies)
-
How to Fill DataSet with more records (around 1 lakh) in a faster way
by Jayaram P (0 replies)
-
Can't print on the network with MSADESS ??
by anatha1 (2 replies)
-
How to POP3 in C#
by converter2009 (9 replies)
-
Very Urgent regarding deleting the images from a folder
by Nanosteps (6 replies)
Related podcasts
-
Object-Oriented Programming in Ruby
In this episode, I talk with Scott Bellware about object-oriented programming in Ruby, and Ruby's object model. This is taken from a private conversation, and the audio quality suffers at times. Much thanks to Scott for allowing this to be released.This episode of the Alt.NET Podcast is bro...
hello I want to send an object with tcp socket ( a class that i made it). I see here that you r sending string (converted to byte array)
How can i convert a class to byte array so i can send it with this socket???? (the winsock object in C# it takes an "object" parameter and it send it ,this socket can not take anything else except the byte array)
!--removed tag-->If u encounter a Cross-Threading problem u may need to do a little fix. Replace OnDataReceived function in the server side with that code:
!--removed tag-->This tutorial provides just basic network programming knowledge, in order to build high performance client - server solution you need more than that.
Clean and scalable server architecture should be designed. Not easy task at all
I would suggest to take a look at XF.Server component for server solutions written in .NET / C# / VB.NET
The only thing that should be added is the server's business logic. I've tried the component, it has nice design and interesting solutions to get maximum performance.
Hi,
I want to develop an application in C# which is connecting to UNIX server throgh socket and execute Unix commands from c# application. Please send me any sample programe in C# which uses socket programming to connect to unix server and execute unix command.
thanks,
Mak
I want an application , where a single client using more than one server (Same Application running in more than one machines.).Client listening to a single port for all the servers it connected to.
Client application will receive huge data frequently. Server will process and send the data to client.
As i want the application to be started first i made the main application as Server. Am i right.
or Do we have option for passive Servers.
With Thanks,
Eswar
After the client is connected, the server recieves only 1 byte of data.
If I introduce a delay(Thread.Sleep, MBox, or a breakpoint), between the OnClientConnect, WaitForData and OnDataReceived functions, I get complete data.
This shouldn't happen logically. I'm wondering what might be the problem.
Sir i am new to .Net and i want to create chatting software which can communicate over the internet too.
I have searched a lot but the help which i found couldn't solve my problem. Please sir
i have to complete my semester project of Bs(Computer Engineering) i need help.
you can mail me the solution on my email dr_hunaindurrani@yahoo.com i will be great full to you.
Thanks in advance
Hunain Durrani.
Ok, here is the fix to make the samples work under C# 2005 without exceptions.
In the SocketServer project modify the SocketServer class as follows:
1. Add the following delegate declaration:
// This delegate enables asynchronous calls for setting
// the text property on a TextBox control.
delegate void AppendTextCallback(string text);
2. Add the following method:
// If the calling thread is different from the thread that
// created the TextBox control, this method creates a
// AppendTextCallback and calls itself asynchronously using the
// Invoke method.
//
// If the calling thread is the same as the thread that created
// the TextBox control, the Text property is set directly.
private void AppendRxText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.txtDataRx.InvokeRequired)
{
AppendTextCallback d = new AppendTextCallback(AppendRxText);
this.Invoke(d, new object[] { text });
}
else
{
txtDataRx.Text = txtDataRx.Text + text;
}
}
3. Replace the OnDataReceived method with the following, or make the minor one line code change
as commented in the method below if you prefer:
public void OnDataReceived(IAsyncResult asyn)
{
try
{
CSocketPacket theSockId = (CSocketPacket)asyn.AsyncState ;
//end receive...
int iRx = 0 ;
iRx = theSockId.thisSocket.EndReceive (asyn);
char[] chars = new char[iRx + 1];
System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);
System.String szData = new System.String(chars);
// Old offending line
//txtDataRx.Text = txtDataRx.Text + szData;
AppendRxText(szData);
WaitForData(m_socWorker );
}
catch (ObjectDisposedException )
{
System.Diagnostics.Debugger.Log(0,"1","\nOnDataReceived: Socket has been closed\n");
}
catch(SocketException se)
{
MessageBox.Show (se.Message );
}
}
I am using Visual C# 2005. It turns out that there are some cross thread calls to forms controls which are flagged as unsafe when running under C# 2005. I will post fixes to these a little later.
there is aproblem meet me ,i designed aprogram simulate the work of credit card by designing two programs one used by auser and the other one for the administration and deal with database ,but when i put the two program on different computer they are not work
the tcplistner statement as follow:
listener = new TcpListener(1500);
the tcpclient statement as follow:
client = new TcpClient("192.168.1.1", 1500);
since the "192.168.1.1" is the ip address of the machine that the server program run at
How can we reduce this timeout?
What is the method to control it?
Thanks
assalam-o-aleykum, im raheel from pakistan, and i want to know about client to client messanger, plz guide me. thanks. my mail raheel_s81@hotmail.com
Hi
I am trying server request/response program using socket class. here i couldn't send headers with the request to the proxy server.when i send the request i should able to get the response from the server.
if u have any idea please help me out.
Regards
request.
Regarding blocking socket calls. Are u assuming .net does the polling. As no additional code has to be written for polling. So no need to return to main thread and a delegate also is not required.
Now consider in asynchronous mode, multiple clients are connected. Then the delegates for beginreceive will fire at will and when multiple fire at same time, it gets stacked as there only one thread. Then the last delegate to be fired will be processed and then down the stack. In fact if we need to sequence something, a lot of coding is involved. The flow also is not clear and criss crosses.
Could you comment on the above. I have a req which needs sequential access of the messages and depends on a flow mapping of messages when there are multiple clients. I been thinking async(with delegates) will be an overhead and confusing/complicated to implement.
When the Client tries to connect to a disconnected IP address, there is a long timeout of 23 seconds...
How can we reduce this timeout?
What is the method to control it?
Thanks for help
you can do client / server in the same computer by useing concept "localhost" if you send to my your program i will correct to you and send to you .
and also i try to do multi client / server in c# programming if you can help my after .
I only speak a lite bit of english.
I would like to know how to run the server and the client in the
same computer to text my application before to start with two
diferents computers.
Thank Javier
This thread is for discussions of Socket Programming in C# - Part 1.