Library tutorials & articles

Socket Programming in C# - Part 1

Making a Connection and Sending Data

With this info lets now try to check the code behind this:

Socket programming in .NET is made possible by the Socket class present inside the System.Net.Sockets namespace. This Socket class has several method and properties and a constructor. The first step is to create an object of this class. Since there is only one constructor we have no choice but to use it.

Here is how to create the socket:

m_socListener = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

The first parameter is the address family which we will use, in this case, interNetwork (which is IP version 4) - other options include Banyan NetBios, AppleTalk etc. (AddressFamily is an enum defined in Sockets namespace). Next we need to specify socket type: and we would use reliable two way connection-based sockets (stream) instead of un-reliable Connectionless sockets (datagrams) . So we obviously specify stream as the socket type and finally we are using TCP/IP so we would specify protocol type as Tcp.

Once we have created a Socket we need to make a connection to the server since we are using connection-based communication. To connect to the remote computer we need to know the IP Address and port at which to connect. In .NET there is a class under System.Net namespace called IPEndPoint which represents a network computer as an IP address and a port number. The IPEndPoint has two constructors - one that takes a IP Address and Port number and one that takes long and port number. Since we have computer IP address we would use the former

public IPEndPoint(System.Net.IPAddress address, int port);

As you can see the first parameter takes a IPAddress object. If you examine the IPAddress class you will see that it has a static method called Parse that returns IPAddress given a string (of dot notation) and second parameter will be the port number. Once we have endpoint ready we can use Connect method of this Socket class to connect to the end point ( remote server computer ). Here is the code:

System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse("10.10.101.200");
System.Net.IPEndPoint remoteEP = new IPEndPoint (iAdd,8221);
m_socClient.Connect (remoteEP);

These three lines of code will make a connection to the remote host running on computer with IP 10.10.101.200 and listening at port 8221. If the Server is running and started ( listening ), the connection will succeed. If however the server is not running an exception called SocketException will be thrown. If you catch the exception and check the Message property of the exception in this case you see following text:

"No connection could be made because the target machine actively refused it."

Similarly if you already have made a connection and the server somehow dies , you will get following exception if you try to send data.

"An existing connection was forcibly closed by the remote host"

Assuming that the connection is made, you can send data to other side using the Send method of the Socket class. Send method has several overloads. All of them take a byte array . For example if you want to send "Hello There" to host you can use following call:

try
{
    String szData = "Hello There";
    byte[] byData = System.Text.Encoding.ASCII.GetBytes(szData);
    m_socClient.Send(byData);
}
catch (SocketException se)
{
    MessageBox.Show ( se.Message );
}

Note that the Send method is blocking. This means the call will block (wait) till the data has been sent or an exception has been thrown. There is an non-blocking version of the send which we will discuss in the next part of this article. Similar to Send there is a Receive method on the Socket class. You can receive data using following call:

byte [] buffer = new byte[1024];
int iRx = m_socClient.Receive (buffer);

The Receive method again is blocking. It means that if there is no data available the call will block until some data arrives or an exception is thrown.
Non-blocking version of Receive method is more useful than the non-blocking version of Send because if we opt for block Receive , we are effectively doing polling. There is no events about data arrival. This model does not work well for serious applications. But all that is the subject of our next part of this article. For now we will settle with the blocking version.

AddThis

Comments

  1. 29 Sep 2008 at 07:35

    sir, could you please help me regarding the socket programming beyond firewalls in .NET framework please send me the code required

    thanks and regards kancherlasravan

  2. 05 Apr 2008 at 23:30

    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 Geeked 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.

  3. 05 Nov 2007 at 19:01

    I use the neokernel web server for socket communications from my C# applications, it has a model for writing plug-ins using VB or C# and several sample projects for visual studio.

  4. 03 Oct 2007 at 15:40

    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

     

  5. 03 May 2007 at 13:30

    all i haft to say is that this is a very informative tutorial and i'd recommend it to anyone who wants to try building socket based software in C#.

  6. 10 Apr 2007 at 13:26

    Hi,

     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

     

















  7. 15 Mar 2007 at 16:41

    I'm having Interoperability problems with a Java client. The Java Client connects to a TCP server application, and immediately sends some data, and closes the connection.
    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.






  8. 25 Feb 2007 at 22:19

    Hello spowens,

    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.









  9. 19 Jan 2006 at 18:22

    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 );
       }
              }

  10. 19 Jan 2006 at 18:00

    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.  

  11. 17 Oct 2005 at 13:41

    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

  12. 16 Jul 2005 at 12:40

    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

  13. 06 Apr 2005 at 02:54

    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

  14. 07 Mar 2005 at 12:37

    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.



  15. 13 Nov 2003 at 06:58

    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.

  16. 30 Oct 2003 at 05:39

    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

  17. 30 Sep 2003 at 10:41

    hello my name hamza , my email hamzahwh@yahoo.com


    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 .

  18. 25 Aug 2003 at 11:02

    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

Leave a comment

Sign in or Join us (it's free).

Related discussion

Events coming up

  • Nov 19

    C# 3.0 and LINQ with Visual Studio 2008 Training Course

    London, United Kingdom

    This course has been developed to help existing C#.NET 2.0 programmers and developers upgrade their .NET development skills and learn about the new features of Microsoft's C# 3.0 and LINQ to XML and ADO.NET using Visual Studio 2008 (currently codenamed Orcas).