www.xbdev.net
xbdev - software development
Friday March 29, 2024
home | contact | Support | Programming.. With C# and .Net...
>>
     
 

Programming..

With C# and .Net...

 


Sockets and C#

 

As with everything, we must start somewhere, and that somewhere is here at main()...  If you look around the net...there's a ton of information on sockets out there.  And once you get past the basics of what a socket is and why we need them, you'll soon realise that they aren't that bad.  I'll be showing you how to use the very basics of setting up sockets using C#...so that you can receive or send some data to an IP address.

 

Code:

// files.cs

 

class abc

{

      static void Main()

      {

            /* our program entry point*/

      }

}

 

But to make things interesting...we'll be connecting to a server... a web server...google.com in this tutorial...  Now when we connect we'll get the html code and put it to a text file....we'll also put some debug info to a text file, so we can see our code step by step.... so lets write our text output code first:

 

Code:

class debug

{

      public static void abc(string str)

      {

            // FileMode - Append, Create, CreateNew, Open, OpenOrCreate, or Truncate

            // FileAccess - Read, ReadWrite, or Write

 

            // Read the whole file contents in

            FileStream file = new FileStream("abc.txt", FileMode.OpenOrCreate | FileMode.Append, FileAccess.Write);

 

 

            // Create a new stream to read from a file

            StreamWriter f = new StreamWriter(file);

 

            f.Write(str);

 

            // Close StreamReader

            f.Close();

 

            // Close file

            file.Close();

      }// End of abc(..)

 

}// End of class abc

 

So when we need to put data to our file...we can do this:

 

debug.abc("Starting Point A\r\n");

...code

debug.abc("Reached Point B\r\n");

 

Simple eh?... Well it will come in really useful as we go step by step through our code :)

 

 

Code:

using System.Net.Sockets;  // Socket

using System.Net;          // IPEndPoint

 

class debug

[..]

 

 

// Blocking sockets entry point of program

class Program

{

      static void Main()

      {

            debug.abc("Setting Up Socket:\r\n");

            //                            +-- an enum, which defines which networking we want to

            //                            |   use, InterNetwork implies IP v 4

            //                            |

            //                            |                       +- Socket type - reliable or

            //                            |                       |                 unreliable

            //                            |                       |

            //                            |                       |                 +- Protocol

            //                            |                       |                 |

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

            debug.abc("Socket s: " + s.ToString() + "\r\n");

      }

}

 

 

Setting Up Socket:
Socket s: System.Net.Sockets.Socket

 

Simple... but its not given us much yet...  But its worth noting that C# isn't like C or C++.... as we can't just check the return value of a Socket.  You'll find that if you can't open a socket, the application will throw an exception error which you must catch and deal with.

 

Code:

class Program

{

      static void Main()

      {

            // google.com -> 216.239.53.99:80

 

            debug.abc("Setting Up Socket:\r\n");

            //                            +-- an enum, which defines which networking we want to

            //                            |   use, InterNetwork implies IP v 4

            //                            |

            //                            |                       +- Socket type - reliable or

            //                            |                       |                 unreliable

            //                            |                       |

            //                            |                       |                 +- Protocol

            //                            |                       |                 |

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

 

            // Connect to our server

            debug.abc("Connecting to Server:\r\n");

            int port = 80;

            System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse("216.239.53.99");

            IPEndPoint cc = new IPEndPoint( ipAdd, port );

 

            s.Connect(cc);

 

            if( !s.Connected ) debug.abc("unable to connect" );

      }

}

 

Or just in case you don't know the IP address, you can use the following snippet :)

 

Snippet:

            IPHostEntry IPHost = Dns.Resolve("www.google.com");

            IPAddress[] addr = IPHost.AddressList;

            IPEndPoint cc = new IPEndPoint( addr[0], port );

 

Lets send the command to the 'google' server for the html code... which is 'Get \r\n\r\n'... and in response the server will send the html text back.

 

Code:

class Program

{

      static void Main()

      {

            // google.com -> 216.239.53.99:80

 

            debug.abc("Setting Up Socket:\r\n");

            //                            +-- an enum, which defines which networking we want to

            //                            |   use, InterNetwork implies IP v 4

            //                            |

            //                            |                       +- Socket type - reliable or

            //                            |                       |                 unreliable

            //                            |                       |

            //                            |                       |                 +- Protocol

            //                            |                       |                 |

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

 

            // Connect to our server

            debug.abc("Connecting to Server:\r\n");

            int port = 80;

            System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse("216.239.53.99");

            IPEndPoint cc = new IPEndPoint( ipAdd, port );

 

            s.Connect(cc);

 

            // Send the request for the html

            debug.abc("Sending:\r\n");

            string szData = "GET / HTTP/1.0\r\n\r\n";

            byte[] byData = System.Text.Encoding.ASCII.GetBytes(szData);

            s.Send(byData, byData.Length, 0);

 

            // Receiving the html from the server

            debug.abc("Receive:\r\n");

            byte [] buffer = new byte[1024];

            int iRx = s.Receive (buffer, buffer.Length, 0);

            string received = System.Text.Encoding.ASCII.GetString(buffer, 0, iRx);

            debug.abc(received);

 

            s.Close();

      }// End of Main()

}// End of class Program

 

 

txt file:
Connecting to Server:
Sending:
Receive:
HTTP/1.0 200 OK
Connection: Keep-Alive
Date: Tue, 07 Oct 2003 12:55:03 GMT
Content-length: 2690
Server: GWS/2.1
Content-Type: text/html
Cache-control: private
Set-Cookie: PREF=ID=71fa3ae60e338d94:TM=1065531303:LM=1065531303:S=I4TjlpUJx6giMYjW; expires=Sun, 17-Jan-2038 19:14:07 GMT; path=/; domain=.google.com

<html><head><meta http-equiv=".............(etc)

 

 

One small problem with the code is that it receives the first 1000 bytes....and that could be a problem...what if where being sent a big html file...possibly 12,000 bytes?  Well we can do a small loop and keep receiving the data until we've got it all:

 

Code:
...

            // Receiving default html page

            debug.abc("Receive:\r\n");

 

            int iRxBytes = 1;

            while( iRxBytes > 0 )

            {

                  byte [] buffer = new byte[1024];

                  iRxBytes = s.Receive (buffer, buffer.Length, 0);

 

                  string received = System.Text.Encoding.ASCII.GetString(buffer, 0, iRxBytes);

 

                  debug.abc(received);

            }// End while loop

 

            s.Close();

...

 

 

Okay our code does a simple socket setup....its up to you to experiment and try other things....maybe write a small chat program :)

 

 

 

 
Advert (Support Website)

 
 Visitor:
Copyright (c) 2002-2024 xbdev.net - All rights reserved.
Designated articles, tutorials and software are the property of their respective owners.