Sockets In .net

I found this faq on vbCity.com that seemed usefull for people who want to use sockets in .NET I do not take credit for this document since it was made by WWJD from vbCity.com But it seemed appropriate to post it here. Easier way to use sockets, of course with limitations, ideal for beginning programmers.

url: hxxp://vbcity.com/forums/faq.asp?tid=29475

Introduction
This FAQ introduces the Microsoft.Net® Framework’s Socket class. It demonstrates how to use a Socket object to send and receive some data. The Socket class makes it possible for you to write applications that can connect to other computers through a network, be it a local area network or the internet.

Why should you be interested in learning about the Socket class? Have you considered creating a chat application, a multi-player internet game, or a secure channel for your company’s data? These are a few of the reasons for learning how to program with the Socket class.

Walk Through
The Socket class provides a way for you to add the power of TCP/IP to your application without dealing directly with network protocols, TCP/IP, Berkeley Sockets, Winsock, or the Winsock API.

This walk through shows how to 1) import the System.Net namespaces necessary to implement Sockets; 2) declare Socket, TcpListener, IPEndpoint, and Timer variables; 3) send data with a Socket object; and 4) receive data with a Socket object.

A project created from this walkthrough is attached for reference.

Step One: Import the System.Net namespaces.

Use Visual Studio.Net to create a new Windows application named MySockets. Open the code behind Form1. At the top of the code, above the “Public Class Form1” line, add:

Add the code that will create the Socket object and other objects required for this walkthrough. After the “Windows Form Designer generated code” region in Form1 add:

Code:Private _ClientSocket As Socket
Private _HostSocket As Socket
Private _TcpListener As New TcpListener(5124)
Private _IpEndPoint As New _
IPEndPoint(Dns.GetHostByName(Dns.GetHostName).AddressList(0), 5124)
Private _Timer As New Timer()

NOTE: See the DemoSockets project for important comments about these statements.

The properties and methods of the Socket object provide an interface to TCP/IP. With them an application can establish a connection, monitor the connection, send/receive data, and close the connection. Learn more: Socket Class

An IPEndPoint object represents a network endpoint as an IP address and a port number. The _IpEndPoint declaration above uses shared methods of the Dns Class to get the internet bound address of the computer:

Code:Dns.GetHostByName(Dns.GetHostName).AddressList(0)

Learn more: Dns Class

STEP THREE: Send data with a Socket.

The SendButton_Click subroutine in the SocketsDemo project uses the _ClientSocket object to send data to network end point contained in the _IPEndPoint object.

Code:Private Sub SendButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)_
Handles SendButton.Click
' Instantiate a new Socket object and
' assign a reference to it to the _ClientSocket variable.
' AddressFamily.InterNetwork is an
' address which meets the IP protocol version 4 standard.
' SocketType.Stream supports reliable, two-way,
' connection-based byte streams without the duplication
' of data and without preservation of boundaries.
' ProtocolType.Tcp = Transmission Control Protocol
_ClientSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
' Call the Socket Connection method passing it the IP
' address and port of this computer (_IpEndPoint)
' This establish the Sockets connection to a remote device.
_ClientSocket.Connect(_IpEndPoint)
' Convert sendData (string) into a Byte array.
Dim Buffer() As Byte = System.Text.ASCIIEncoding.ASCII.GetBytes(ClientMessageTextBox.Text)
' _ClientSocket sends the data to port 5124.
_ClientSocket.Send(Buffer, 0, Buffer.Length, SocketFlags.None)
' Enable _Timer so the CheckListener method will be called every 1 second.
' Set _Timer interval to 1 second.
_Timer.Interval = 1000
' Start the timer.
_Timer.Start()
' Call the Socket Shutdown method passing it the
' SocketShutDown.Both parameter.
' This disables sends and receives on the socket.
_ClientSocket.Shutdown(SocketShutdown.Both)
' Call the Socket Close method to close the socket.
' Forces a socket connection to close.
_ClientSocket.Close()
End Sub

Here are some key points from concerning the subroutine.

_ClientSocket is assigned a new Socket object.

The _ClientSocket is passed the _IPEndPoint object when its Connect method is called. This opens a connection to an end point on the network.

To send a String through the network it must be converted into a byte array. In the subroutine an ASCIIEncoding object’s GetBytes method is used to convert the text from the ClientMessageTextBox into bytes which are used to fill the Buffer() byte array.

The data is sent using the _ClientSocket’s Send method.

The _Timer object is set/started to raise a Tick event every second.

The _SocketObject’s ShutDown and Close methods must be called after the data has been sent.

STEP FOUR: Receive data with a Socket object.

The CheckTcpListener subroutine in the SocketsDemo project uses a Socket object to received data.

Code:Private Sub CheckTcpListener(ByVal sender As Object, ByVal e As System.EventArgs)
' This method is called every second when _Timer is running.

' Call the Socket Poll method to determine if the status of _HostSocket
' is SelectRead which means data is available to read.
If _HostSocket.Poll(1, SelectMode.SelectRead) Then
' _HostSocket has data to be read.
' Call the Socket Available method on _HostSocket;
' assign the return value (Bytes available) to an integer variable.
Dim numBytes As Int32 = _HostSocket.Available
' Instantiate an array of Bytes which is the size of the
' number of Bytes available.
Dim Data(numBytes) As Byte
' Call the Socket Receive method.
' Receives data from a connected Socket.
_HostSocket.Receive(Data)
' Convert the Byte array received into a String
HostMessagesReceivedTextBox.Text &= System.Text.ASCIIEncoding.ASCII.GetString(Data)
HostMessagesReceivedTextBox.Text &= ControlChars.CrLf
' Stop _Timer. Message was received and processed.
_Timer.Stop()
End If
End If
End Sub

When the _Timer object raises a Tick event the CheckTcpListner subroutine handles the Tick event. Here are some key points from this subroutine.

A TcpListner object must be checked for a pending connection, it does not raise a connection pending event.

A TcpListner object must pass a pending connection to a Socket for further processing so it can go back to listening for connections.

When a Socket object is passed a connection it must be polled to determine the state of the socket. In the DemoSockets project the _HostSocket object is polled for the SelectMode.SelectRead state. The SelectMode.SelectRead state indicates the Socket received data.

The Socket object’s Available property gets the number of bytes of data that has been received from the network – the bytes that are available to be read.

The data must be received into a byte array then converted to characters. At this point encoding is used to convert a array of bytes to characters. In the DemoSockets project the GetString method of an ASCIIEncoding object is used to convert the byte arrray to a String.

IMPORTANT: For simplicty’s sake, error handling was left out of the SocketsDemo. A real-world application should wrap the code that imlements sockets with Try..Finally exception handlers which will close the Socket should and error occur. A socket uses Windows OS resources which should not be left in an open state if an error occurs.

Conclusion
The .Net Framework’s Socket class is your gateway to the TCP/IP world. Add the power of TCP/IP to your applications with Sockets.

This FAQ is has been a small introduction to how to use Sockets. Visit the links provided in the FAQ to learn more