<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-6709431659636147588</id><updated>2011-05-05T19:02:31.838-07:00</updated><category term='c#'/><category term='server'/><category term='program'/><category term='socket'/><category term='synchronous'/><category term='dotnet'/><category term='client'/><category term='asynchronous'/><category term='java'/><category term='vb'/><category term='tutorial'/><title type='text'>Class library socket programming for .NET and JAVA</title><subtitle type='html'>Here, you can find library for socket programming, now available for .NET (C#,VB) and java.</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://www.myg3nx.co.cc/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6709431659636147588/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://www.myg3nx.co.cc/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>haries</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>8</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-6709431659636147588.post-5287755522919367840</id><published>2011-05-05T18:53:00.000-07:00</published><updated>2011-05-05T18:53:46.708-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='server'/><category scheme='http://www.blogger.com/atom/ns#' term='socket'/><category scheme='http://www.blogger.com/atom/ns#' term='asynchronous'/><category scheme='http://www.blogger.com/atom/ns#' term='dotnet'/><title type='text'>Tutorial Asynchronous Socket Programming using .NET (For Server)</title><content type='html'>The following example program creates a server that receives connection requests from clients. The server is built with an asynchronous socket, so execution of the server application is not suspended while it waits for a connection from a client. The application receives a string from the client, displays the string on the console, and then echoes the string back to the client. The string from the client must contain the string "&lt;eof&gt;" to signal the end of the message.&lt;br /&gt;&lt;/eof&gt;&lt;br /&gt;&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For VB&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;Imports System&lt;br /&gt;Imports System.Net&lt;br /&gt;Imports System.Net.Sockets&lt;br /&gt;Imports System.Text&lt;br /&gt;Imports System.Threading&lt;br /&gt;Imports Microsoft.VisualBasic&lt;br /&gt;&lt;br /&gt;' State object for reading client data asynchronously&lt;br /&gt;&lt;br /&gt;Public Class StateObject&lt;br /&gt;    ' Client  socket.&lt;br /&gt;    Public workSocket As Socket = Nothing&lt;br /&gt;    ' Size of receive buffer.&lt;br /&gt;    Public Const BufferSize As Integer = 1024&lt;br /&gt;    ' Receive buffer.&lt;br /&gt;    Public buffer(BufferSize) As Byte&lt;br /&gt;    ' Received data string.&lt;br /&gt;    Public sb As New StringBuilder&lt;br /&gt;End Class 'StateObject&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Public Class AsynchronousSocketListener&lt;br /&gt;    ' Thread signal.&lt;br /&gt;    Public Shared allDone As New ManualResetEvent(False)&lt;br /&gt;&lt;br /&gt;    ' This server waits for a connection and then uses  asychronous operations to&lt;br /&gt;    ' accept the connection, get data from the connected client, &lt;br /&gt;    ' echo that data back to the connected client.&lt;br /&gt;    ' It then disconnects from the client and waits for another client. &lt;br /&gt;    Public Shared Sub Main()&lt;br /&gt;        ' Data buffer for incoming data.&lt;br /&gt;        Dim bytes() As Byte = New [Byte](1023) {}&lt;br /&gt;&lt;br /&gt;        ' Establish the local endpoint for the socket.&lt;br /&gt;        Dim ipHostInfo As IPHostEntry = Dns.Resolve(Dns.GetHostName())&lt;br /&gt;        Dim ipAddress As IPAddress = ipHostInfo.AddressList(0)&lt;br /&gt;        Dim localEndPoint As New IPEndPoint(ipAddress, 11000)&lt;br /&gt;&lt;br /&gt;        ' Create a TCP/IP socket.&lt;br /&gt;        Dim listener As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)&lt;br /&gt;&lt;br /&gt;        ' Bind the socket to the local endpoint and listen for incoming connections.&lt;br /&gt;        listener.Bind(localEndPoint)&lt;br /&gt;        listener.Listen(100)&lt;br /&gt;&lt;br /&gt;        While True&lt;br /&gt;            ' Set the event to nonsignaled state.&lt;br /&gt;            allDone.Reset()&lt;br /&gt;&lt;br /&gt;            ' Start an asynchronous socket to listen for connections.&lt;br /&gt;            Console.WriteLine("Waiting for a connection...")&lt;br /&gt;            listener.BeginAccept(New AsyncCallback(AddressOf AcceptCallback), listener)&lt;br /&gt;&lt;br /&gt;            ' Wait until a connection is made and processed before continuing.&lt;br /&gt;            allDone.WaitOne()&lt;br /&gt;        End While&lt;br /&gt;    End Sub 'Main&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    Public Shared Sub AcceptCallback(ByVal ar As IAsyncResult)&lt;br /&gt;        ' Get the socket that handles the client request.&lt;br /&gt;        Dim listener As Socket = CType(ar.AsyncState, Socket)&lt;br /&gt;        ' End the operation.&lt;br /&gt;        Dim handler As Socket = listener.EndAccept(ar)&lt;br /&gt;&lt;br /&gt;        ' Create the state object for the async receive.&lt;br /&gt;        Dim state As New StateObject&lt;br /&gt;        state.workSocket = handler&lt;br /&gt;        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)&lt;br /&gt;    End Sub 'AcceptCallback&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    Public Shared Sub ReadCallback(ByVal ar As IAsyncResult)&lt;br /&gt;        Dim content As String = String.Empty&lt;br /&gt;&lt;br /&gt;        ' Retrieve the state object and the handler socket&lt;br /&gt;        ' from the asynchronous state object.&lt;br /&gt;        Dim state As StateObject = CType(ar.AsyncState, StateObject)&lt;br /&gt;        Dim handler As Socket = state.workSocket&lt;br /&gt;&lt;br /&gt;        ' Read data from the client socket. &lt;br /&gt;        Dim bytesRead As Integer = handler.EndReceive(ar)&lt;br /&gt;&lt;br /&gt;        If bytesRead &amp;gt; 0 Then&lt;br /&gt;            ' There  might be more data, so store the data received so far.&lt;br /&gt;            state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead))&lt;br /&gt;&lt;br /&gt;            ' Check for end-of-file tag. If it is not there, read &lt;br /&gt;            ' more data.&lt;br /&gt;            content = state.sb.ToString()&lt;br /&gt;            If content.IndexOf("&lt;eof&gt;") &amp;gt; -1 Then&lt;br /&gt;                ' All the data has been read from the &lt;br /&gt;                ' client. Display it on the console.&lt;br /&gt;                Console.WriteLine("Read {0} bytes from socket. " + vbLf + " Data : {1}", content.Length, content)&lt;br /&gt;                ' Echo the data back to the client.&lt;br /&gt;                Send(handler, content)&lt;br /&gt;            Else&lt;br /&gt;                ' Not all data received. Get more.&lt;br /&gt;                handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)&lt;br /&gt;            End If&lt;br /&gt;        End If&lt;br /&gt;    End Sub 'ReadCallback&lt;br /&gt;&lt;br /&gt;    Private Shared Sub Send(ByVal handler As Socket, ByVal data As String)&lt;br /&gt;        ' Convert the string data to byte data using ASCII encoding.&lt;br /&gt;        Dim byteData As Byte() = Encoding.ASCII.GetBytes(data)&lt;br /&gt;&lt;br /&gt;        ' Begin sending the data to the remote device.&lt;br /&gt;        handler.BeginSend(byteData, 0, byteData.Length, 0, New AsyncCallback(AddressOf SendCallback), handler)&lt;br /&gt;    End Sub 'Send&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    Private Shared Sub SendCallback(ByVal ar As IAsyncResult)&lt;br /&gt;        ' Retrieve the socket from the state object.&lt;br /&gt;        Dim handler As Socket = CType(ar.AsyncState, Socket)&lt;br /&gt;&lt;br /&gt;        ' Complete sending the data to the remote device.&lt;br /&gt;        Dim bytesSent As Integer = handler.EndSend(ar)&lt;br /&gt;        Console.WriteLine("Sent {0} bytes to client.", bytesSent)&lt;br /&gt;&lt;br /&gt;        handler.Shutdown(SocketShutdown.Both)&lt;br /&gt;        handler.Close()&lt;br /&gt;        ' Signal the main thread to continue.&lt;br /&gt;        allDone.Set()&lt;br /&gt;    End Sub 'SendCallback&lt;br /&gt;End Class 'AsynchronousSocketListener&lt;br /&gt;&lt;/eof&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For C#&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;using System;&lt;br /&gt;using System.Net;&lt;br /&gt;using System.Net.Sockets;&lt;br /&gt;using System.Text;&lt;br /&gt;using System.Threading;&lt;br /&gt;&lt;br /&gt;// State object for reading client data asynchronously&lt;br /&gt;public class StateObject {&lt;br /&gt;    // Client  socket.&lt;br /&gt;    public Socket workSocket = null;&lt;br /&gt;    // Size of receive buffer.&lt;br /&gt;    public const int BufferSize = 1024;&lt;br /&gt;    // Receive buffer.&lt;br /&gt;    public byte[] buffer = new byte[BufferSize];&lt;br /&gt;// Received data string.&lt;br /&gt;    public StringBuilder sb = new StringBuilder();  &lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public class AsynchronousSocketListener {&lt;br /&gt;    // Thread signal.&lt;br /&gt;    public static ManualResetEvent allDone = new ManualResetEvent(false);&lt;br /&gt;&lt;br /&gt;    public AsynchronousSocketListener() {&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public static void StartListening() {&lt;br /&gt;        // Data buffer for incoming data.&lt;br /&gt;        byte[] bytes = new Byte[1024];&lt;br /&gt;&lt;br /&gt;        // Establish the local endpoint for the socket.&lt;br /&gt;        // The DNS name of the computer&lt;br /&gt;        // running the listener is "host.contoso.com".&lt;br /&gt;        IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());&lt;br /&gt;        IPAddress ipAddress = ipHostInfo.AddressList[0];&lt;br /&gt;        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);&lt;br /&gt;&lt;br /&gt;        // Create a TCP/IP socket.&lt;br /&gt;        Socket listener = new Socket(AddressFamily.InterNetwork,&lt;br /&gt;            SocketType.Stream, ProtocolType.Tcp );&lt;br /&gt;&lt;br /&gt;        // Bind the socket to the local endpoint and listen for incoming connections.&lt;br /&gt;        try {&lt;br /&gt;            listener.Bind(localEndPoint);&lt;br /&gt;            listener.Listen(100);&lt;br /&gt;&lt;br /&gt;            while (true) {&lt;br /&gt;                // Set the event to nonsignaled state.&lt;br /&gt;                allDone.Reset();&lt;br /&gt;&lt;br /&gt;                // Start an asynchronous socket to listen for connections.&lt;br /&gt;                Console.WriteLine("Waiting for a connection...");&lt;br /&gt;                listener.BeginAccept( &lt;br /&gt;                    new AsyncCallback(AcceptCallback),&lt;br /&gt;                    listener );&lt;br /&gt;&lt;br /&gt;                // Wait until a connection is made before continuing.&lt;br /&gt;                allDone.WaitOne();&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;        } catch (Exception e) {&lt;br /&gt;            Console.WriteLine(e.ToString());&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        Console.WriteLine("\nPress ENTER to continue...");&lt;br /&gt;        Console.Read();&lt;br /&gt;        &lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public static void AcceptCallback(IAsyncResult ar) {&lt;br /&gt;        // Signal the main thread to continue.&lt;br /&gt;        allDone.Set();&lt;br /&gt;&lt;br /&gt;        // Get the socket that handles the client request.&lt;br /&gt;        Socket listener = (Socket) ar.AsyncState;&lt;br /&gt;        Socket handler = listener.EndAccept(ar);&lt;br /&gt;&lt;br /&gt;        // Create the state object.&lt;br /&gt;        StateObject state = new StateObject();&lt;br /&gt;        state.workSocket = handler;&lt;br /&gt;        handler.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,&lt;br /&gt;            new AsyncCallback(ReadCallback), state);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public static void ReadCallback(IAsyncResult ar) {&lt;br /&gt;        String content = String.Empty;&lt;br /&gt;        &lt;br /&gt;        // Retrieve the state object and the handler socket&lt;br /&gt;        // from the asynchronous state object.&lt;br /&gt;        StateObject state = (StateObject) ar.AsyncState;&lt;br /&gt;        Socket handler = state.workSocket;&lt;br /&gt;&lt;br /&gt;        // Read data from the client socket. &lt;br /&gt;        int bytesRead = handler.EndReceive(ar);&lt;br /&gt;&lt;br /&gt;        if (bytesRead &amp;gt; 0) {&lt;br /&gt;            // There  might be more data, so store the data received so far.&lt;br /&gt;            state.sb.Append(Encoding.ASCII.GetString(&lt;br /&gt;                state.buffer,0,bytesRead));&lt;br /&gt;&lt;br /&gt;            // Check for end-of-file tag. If it is not there, read &lt;br /&gt;            // more data.&lt;br /&gt;            content = state.sb.ToString();&lt;br /&gt;            if (content.IndexOf("&lt;eof&gt;") &amp;gt; -1) {&lt;br /&gt;                // All the data has been read from the &lt;br /&gt;                // client. Display it on the console.&lt;br /&gt;                Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",&lt;br /&gt;                    content.Length, content );&lt;br /&gt;                // Echo the data back to the client.&lt;br /&gt;                Send(handler, content);&lt;br /&gt;            } else {&lt;br /&gt;                // Not all data received. Get more.&lt;br /&gt;                handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,&lt;br /&gt;                new AsyncCallback(ReadCallback), state);&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;    &lt;br /&gt;    private static void Send(Socket handler, String data) {&lt;br /&gt;        // Convert the string data to byte data using ASCII encoding.&lt;br /&gt;        byte[] byteData = Encoding.ASCII.GetBytes(data);&lt;br /&gt;&lt;br /&gt;        // Begin sending the data to the remote device.&lt;br /&gt;        handler.BeginSend(byteData, 0, byteData.Length, 0,&lt;br /&gt;            new AsyncCallback(SendCallback), handler);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private static void SendCallback(IAsyncResult ar) {&lt;br /&gt;        try {&lt;br /&gt;            // Retrieve the socket from the state object.&lt;br /&gt;            Socket handler = (Socket) ar.AsyncState;&lt;br /&gt;&lt;br /&gt;            // Complete sending the data to the remote device.&lt;br /&gt;            int bytesSent = handler.EndSend(ar);&lt;br /&gt;            Console.WriteLine("Sent {0} bytes to client.", bytesSent);&lt;br /&gt;&lt;br /&gt;            handler.Shutdown(SocketShutdown.Both);&lt;br /&gt;            handler.Close();&lt;br /&gt;&lt;br /&gt;        } catch (Exception e) {&lt;br /&gt;            Console.WriteLine(e.ToString());&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    public static int Main(String[] args) {&lt;br /&gt;        StartListening();&lt;br /&gt;        return 0;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/eof&gt;&lt;/pre&gt;&lt;br /&gt;Asynchronous server sockets use the .NET Framework asynchronous programming model to process network service requests. The Socket class follows the standard .NET Framework asynchronous naming pattern; for example, the synchronous Accept method corresponds to the asynchronous BeginAccept and EndAccept methods.&lt;br /&gt;&lt;br /&gt;An asynchronous server socket requires a method to begin accepting connection requests from the network, a callback method to handle the connection requests and begin receiving data from the network, and a callback method to end receiving the data. All these methods are discussed further in this section.&lt;br /&gt;&lt;br /&gt;In the following example, to begin accepting connection requests from the network, the method StartListening initializes the Socket and then uses the BeginAccept method to start accepting new connections. The accept callback method is called when a new connection request is received on the socket. It is responsible for getting the Socket instance that will handle the connection and handing that Socket off to the thread that will process the request. The accept callback method implements the AsyncCallback delegate; it returns a void and takes a single parameter of type IAsyncResult. The following example is the shell of an accept callback method.&lt;br /&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For VB&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;Sub acceptCallback(ar As IAsyncResult)&lt;br /&gt;    ' Add the callback code here.&lt;br /&gt;End Sub 'acceptCallback&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For C#&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;void acceptCallback( IAsyncResult ar) {&lt;br /&gt;    // Add the callback code here.&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The BeginAccept method takes two parameters, an AsyncCallback delegate that points to the accept callback method and an object that is used to pass state information to the callback method. In the following example, the listening Socket is passed to the callback method through the state parameter. This example creates an AsyncCallback delegate and starts accepting connections from the network.&lt;br /&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For VB&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;listener.BeginAccept( _&lt;br /&gt;    New AsyncCallback(SocketListener.acceptCallback),_&lt;br /&gt;    listener)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For C#&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;listener.BeginAccept(&lt;br /&gt;    new AsyncCallback(SocketListener.acceptCallback), &lt;br /&gt;    listener);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Asynchronous sockets use threads from the system thread pool to process incoming connections. One thread is responsible for accepting connections, another thread is used to handle each incoming connection, and another thread is responsible for receiving data from the connection. These could be the same thread, depending on which thread is assigned by the thread pool. In the following example, the System.Threading..::.ManualResetEvent class suspends execution of the main thread and signals when execution can continue.&lt;br /&gt;&lt;br /&gt;The following example shows an asynchronous method that creates an asynchronous TCP/IP socket on the local computer and begins accepting connections. It assumes that there is a global ManualResetEvent named allDone, that the method is a member of a class named SocketListener, and that a callback method named acceptCallback is defined.&lt;br /&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For VB&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;Public Sub StartListening()&lt;br /&gt;    Dim ipHostInfo As IPHostEntry = Dns.Resolve(Dns.GetHostName())&lt;br /&gt;    Dim localEP = New IPEndPoint(ipHostInfo.AddressList(0), 11000)&lt;br /&gt;    &lt;br /&gt;    Console.WriteLine("Local address and port : {0}", localEP.ToString())&lt;br /&gt;    &lt;br /&gt;    Dim listener As New Socket(localEP.Address.AddressFamily, _&lt;br /&gt;       SocketType.Stream, ProtocolType.Tcp)&lt;br /&gt;    &lt;br /&gt;    Try&lt;br /&gt;        listener.Bind(localEP)&lt;br /&gt;        listener.Listen(10)&lt;br /&gt;        &lt;br /&gt;        While True&lt;br /&gt;            allDone.Reset()&lt;br /&gt;            &lt;br /&gt;            Console.WriteLine("Waiting for a connection...")&lt;br /&gt;            listener.BeginAccept(New _&lt;br /&gt;                AsyncCallback(SocketListener.acceptCallback), _&lt;br /&gt;                listener)&lt;br /&gt;            &lt;br /&gt;            allDone.WaitOne()&lt;br /&gt;        End While&lt;br /&gt;    Catch e As Exception&lt;br /&gt;        Console.WriteLine(e.ToString())&lt;br /&gt;    End Try&lt;br /&gt;    Console.WriteLine("Closing the listener...")&lt;br /&gt;End Sub 'StartListening&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For C#&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;public void StartListening() {&lt;br /&gt;    IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());&lt;br /&gt;    IPEndPoint localEP = new IPEndPoint(ipHostInfo.AddressList[0],11000);&lt;br /&gt;&lt;br /&gt;    Console.WriteLine("Local address and port : {0}",localEP.ToString());&lt;br /&gt;&lt;br /&gt;    Socket listener = new Socket( localEP.Address.AddressFamily,&lt;br /&gt;        SocketType.Stream, ProtocolType.Tcp );&lt;br /&gt;&lt;br /&gt;    try {&lt;br /&gt;        listener.Bind(localEP);&lt;br /&gt;        listener.Listen(10);&lt;br /&gt;&lt;br /&gt;        while (true) {&lt;br /&gt;            allDone.Reset();&lt;br /&gt;&lt;br /&gt;            Console.WriteLine("Waiting for a connection...");&lt;br /&gt;            listener.BeginAccept(&lt;br /&gt;                new AsyncCallback(SocketListener.acceptCallback), &lt;br /&gt;                listener );&lt;br /&gt;&lt;br /&gt;            allDone.WaitOne();&lt;br /&gt;        }&lt;br /&gt;    } catch (Exception e) {&lt;br /&gt;        Console.WriteLine(e.ToString());&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    Console.WriteLine( "Closing the listener...");&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The accept callback method (acceptCallback in the preceding example) is responsible for signaling the main application thread to continue processing, establishing the connection with the client, and starting the asynchronous read of data from the client. The following example is the first part of an implementation of the acceptCallback method. This section of the method signals the main application thread to continue processing and establishes the connection to the client. It assumes a global ManualResetEvent named allDone.&lt;br /&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For VB&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;Public Sub acceptCallback(ar As IAsyncResult)&lt;br /&gt;    allDone.Set()&lt;br /&gt;    &lt;br /&gt;    Dim listener As Socket = CType(ar.AsyncState, Socket)&lt;br /&gt;    Dim handler As Socket = listener.EndAccept(ar)&lt;br /&gt;&lt;br /&gt;    ' Additional code to read data goes here.&lt;br /&gt;End Sub 'acceptCallback&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For C#&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;public void acceptCallback(IAsyncResult ar) {&lt;br /&gt;    allDone.Set();&lt;br /&gt;&lt;br /&gt;    Socket listener = (Socket) ar.AsyncState;&lt;br /&gt;    Socket handler = listener.EndAccept(ar);&lt;br /&gt;&lt;br /&gt;    // Additional code to read data goes here.  &lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Reading data from a client socket requires a state object that passes values between asynchronous calls. The following example implements a state object for receiving a string from the remote client. It contains fields for the client socket, a data buffer for receiving data, and a StringBuilder for creating the data string sent by the client. Placing these fields in the state object allows their values to be preserved across multiple calls to read data from the client socket.&lt;br /&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For VB&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;Public Class StateObject&lt;br /&gt;    Public workSocket As Socket = Nothing&lt;br /&gt;    Public BufferSize As Integer = 1024&lt;br /&gt;    Public buffer(BufferSize) As Byte&lt;br /&gt;    Public sb As New StringBuilder()&lt;br /&gt;End Class 'StateObject&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For C#&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;public class StateObject {&lt;br /&gt;    public Socket workSocket = null;&lt;br /&gt;    public const int BufferSize = 1024;&lt;br /&gt;    public byte[] buffer = new byte[BufferSize];&lt;br /&gt;    public StringBuilder sb = new StringBuilder();&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The section of the acceptCallback method that starts receiving the data from the client socket first initializes an instance of the StateObject class and then calls the BeginReceive method to start reading the data from the client socket asynchronously.&lt;br /&gt;&lt;br /&gt;The following example shows the complete acceptCallback method. It assumes that there is a global ManualResetEvent named allDone, that the StateObject class is defined, and that the readCallback method is defined in a class named SocketListener.&lt;br /&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For VB&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;Public Shared Sub acceptCallback(ar As IAsyncResult)&lt;br /&gt;    ' Get the socket that handles the client request.&lt;br /&gt;    Dim listener As Socket = CType(ar.AsyncState, Socket)&lt;br /&gt;    Dim handler As Socket = listener.EndAccept(ar)&lt;br /&gt;    &lt;br /&gt;    ' Signal the main thread to continue.&lt;br /&gt;    allDone.Set()&lt;br /&gt;    &lt;br /&gt;    ' Create the state object.&lt;br /&gt;    Dim state As New StateObject()&lt;br /&gt;    state.workSocket = handler&lt;br /&gt;    handler.BeginReceive(state.buffer, 0, state.BufferSize, 0, _&lt;br /&gt;        AddressOf AsynchronousSocketListener.readCallback, state)&lt;br /&gt;End Sub 'acceptCallback&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For C#&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;public static void acceptCallback(IAsyncResult ar) {&lt;br /&gt;        // Get the socket that handles the client request.&lt;br /&gt;        Socket listener = (Socket) ar.AsyncState;&lt;br /&gt;        Socket handler = listener.EndAccept(ar);&lt;br /&gt;&lt;br /&gt;        // Signal the main thread to continue.&lt;br /&gt;        allDone.Set();&lt;br /&gt;&lt;br /&gt;        // Create the state object.&lt;br /&gt;        StateObject state = new StateObject();&lt;br /&gt;        state.workSocket = handler;&lt;br /&gt;        handler.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,&lt;br /&gt;            new AsyncCallback(AsynchronousSocketListener.readCallback), state);&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The final method that needs to be implemented for the asynchronous socket server is the read callback method that returns the data sent by the client. Like the accept callback method, the read callback method is an AsyncCallback delegate. This method reads one or more bytes from the client socket into the data buffer and then calls the BeginReceive method again until the data sent by the client is complete. Once the entire message has been read from the client, the string is displayed on the console and the server socket handling the connection to the client is closed.&lt;br /&gt;&lt;br /&gt;The following sample implements the readCallback method. It assumes that the StateObject class is defined.&lt;br /&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For VB&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;Public Shared Sub readCallback(ar As IAsyncResult)&lt;br /&gt;    Dim state As StateObject = CType(ar.AsyncState, StateObject)&lt;br /&gt;    Dim handler As Socket = state.workSocket&lt;br /&gt;    &lt;br /&gt;    ' Read data from the client socket. &lt;br /&gt;    Dim read As Integer = handler.EndReceive(ar)&lt;br /&gt;    &lt;br /&gt;    ' Data was read from the client socket.&lt;br /&gt;    If read &amp;gt; 0 Then&lt;br /&gt;        state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, read))&lt;br /&gt;        handler.BeginReceive(state.buffer, 0, state.BufferSize, 0, _&lt;br /&gt;            AddressOf readCallback, state)&lt;br /&gt;    Else&lt;br /&gt;        If state.sb.Length &amp;gt; 1 Then&lt;br /&gt;            ' All the data has been read from the client;&lt;br /&gt;            ' display it on the console.&lt;br /&gt;            Dim content As String = state.sb.ToString()&lt;br /&gt;            Console.WriteLine("Read {0} bytes from socket." + _&lt;br /&gt;                ControlChars.Cr + " Data : {1}", content.Length, content)&lt;br /&gt;        End If&lt;br /&gt;    End If&lt;br /&gt;End Sub 'readCallback&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For C#&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;public static void readCallback(IAsyncResult ar) {&lt;br /&gt;    StateObject state = (StateObject) ar.AsyncState;&lt;br /&gt;    Socket handler = state.WorkSocket;&lt;br /&gt;&lt;br /&gt;    // Read data from the client socket.&lt;br /&gt;    int read = handler.EndReceive(ar);&lt;br /&gt;&lt;br /&gt;    // Data was read from the client socket.&lt;br /&gt;    if (read &amp;gt; 0) {&lt;br /&gt;        state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,read));&lt;br /&gt;        handler.BeginReceive(state.buffer,0,StateObject.BufferSize, 0,&lt;br /&gt;            new AsyncCallback(readCallback), state);&lt;br /&gt;    } else {&lt;br /&gt;        if (state.sb.Length &amp;gt; 1) {&lt;br /&gt;            // All the data has been read from the client;&lt;br /&gt;            // display it on the console.&lt;br /&gt;            string content = state.sb.ToString();&lt;br /&gt;            Console.WriteLine("Read {0} bytes from socket.\n Data : {1}",&lt;br /&gt;               content.Length, content);&lt;br /&gt;        }&lt;br /&gt;        handler.Close();&lt;br /&gt;    }&lt;br /&gt;}&amp;nbsp;&lt;/pre&gt;&lt;pre&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre&gt;Download project and code &lt;a href="http://www.ziddu.com/download/14698067/asynchronous_client_server_net.rar.html"&gt;here&lt;/a&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6709431659636147588-5287755522919367840?l=www.myg3nx.co.cc' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.myg3nx.co.cc/feeds/5287755522919367840/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.myg3nx.co.cc/2011/05/tutorial-asynchronous-socket.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6709431659636147588/posts/default/5287755522919367840'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6709431659636147588/posts/default/5287755522919367840'/><link rel='alternate' type='text/html' href='http://www.myg3nx.co.cc/2011/05/tutorial-asynchronous-socket.html' title='Tutorial Asynchronous Socket Programming using .NET (For Server)'/><author><name>haries</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6709431659636147588.post-34977471967274617</id><published>2011-04-21T23:35:00.000-07:00</published><updated>2011-05-05T18:36:04.692-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='socket'/><category scheme='http://www.blogger.com/atom/ns#' term='asynchronous'/><category scheme='http://www.blogger.com/atom/ns#' term='dotnet'/><category scheme='http://www.blogger.com/atom/ns#' term='client'/><title type='text'>Tutorial Asynchronous Socket Programming using .NET (For Client)</title><content type='html'>The following example program creates a client that connects to a server. The client is built with an asynchronous socket, so execution of the client application is not suspended while the server returns a response. The application sends a string to the server and then displays the string returned by the server on the console.&lt;br /&gt;&lt;br /&gt;&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For VB&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;Imports System&lt;br /&gt;Imports System.Net&lt;br /&gt;Imports System.Net.Sockets&lt;br /&gt;Imports System.Threading&lt;br /&gt;Imports System.Text&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;' State object for receiving data from remote device.&lt;br /&gt;&lt;br /&gt;Public Class StateObject&lt;br /&gt;    ' Client socket.&lt;br /&gt;    Public workSocket As Socket = Nothing&lt;br /&gt;    ' Size of receive buffer.&lt;br /&gt;    Public Const BufferSize As Integer = 256&lt;br /&gt;    ' Receive buffer.&lt;br /&gt;    Public buffer(BufferSize) As Byte&lt;br /&gt;    ' Received data string.&lt;br /&gt;    Public sb As New StringBuilder&lt;br /&gt;End Class 'StateObject&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Public Class AsynchronousClient&lt;br /&gt;    ' The port number for the remote device.&lt;br /&gt;    Private Const port As Integer = 11000&lt;br /&gt;&lt;br /&gt;    ' ManualResetEvent instances signal completion.&lt;br /&gt;    Private Shared connectDone As New ManualResetEvent(False)&lt;br /&gt;    Private Shared sendDone As New ManualResetEvent(False)&lt;br /&gt;    Private Shared receiveDone As New ManualResetEvent(False)&lt;br /&gt;&lt;br /&gt;    ' The response from the remote device.&lt;br /&gt;    Private Shared response As String = String.Empty&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    Public Shared Sub Main()&lt;br /&gt;        ' Establish the remote endpoint for the socket.&lt;br /&gt;        ' For this example use local machine.&lt;br /&gt;        Dim ipHostInfo As IPHostEntry = Dns.Resolve(Dns.GetHostName())&lt;br /&gt;        Dim ipAddress As IPAddress = ipHostInfo.AddressList(0)&lt;br /&gt;        Dim remoteEP As New IPEndPoint(ipAddress, port)&lt;br /&gt;&lt;br /&gt;        ' Create a TCP/IP socket.&lt;br /&gt;        Dim client As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)&lt;br /&gt;&lt;br /&gt;        ' Connect to the remote endpoint.&lt;br /&gt;        client.BeginConnect(remoteEP, New AsyncCallback(AddressOf ConnectCallback), client)&lt;br /&gt;&lt;br /&gt;        ' Wait for connect.&lt;br /&gt;        connectDone.WaitOne()&lt;br /&gt;&lt;br /&gt;        ' Send test data to the remote device.&lt;br /&gt;        Send(client, "This is a test&lt;eof&gt;")&lt;br /&gt;        sendDone.WaitOne()&lt;br /&gt;&lt;br /&gt;        ' Receive the response from the remote device.&lt;br /&gt;        Receive(client)&lt;br /&gt;        receiveDone.WaitOne()&lt;br /&gt;&lt;br /&gt;        ' Write the response to the console.&lt;br /&gt;        Console.WriteLine("Response received : {0}", response)&lt;br /&gt;&lt;br /&gt;        ' Release the socket.&lt;br /&gt;        client.Shutdown(SocketShutdown.Both)&lt;br /&gt;        client.Close()&lt;br /&gt;    End Sub 'Main&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    Private Shared Sub ConnectCallback(ByVal ar As IAsyncResult)&lt;br /&gt;        ' Retrieve the socket from the state object.&lt;br /&gt;        Dim client As Socket = CType(ar.AsyncState, Socket)&lt;br /&gt;&lt;br /&gt;        ' Complete the connection.&lt;br /&gt;        client.EndConnect(ar)&lt;br /&gt;&lt;br /&gt;        Console.WriteLine("Socket connected to {0}", client.RemoteEndPoint.ToString())&lt;br /&gt;&lt;br /&gt;        ' Signal that the connection has been made.&lt;br /&gt;        connectDone.Set()&lt;br /&gt;    End Sub 'ConnectCallback&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    Private Shared Sub Receive(ByVal client As Socket)&lt;br /&gt;&lt;br /&gt;        ' Create the state object.&lt;br /&gt;        Dim state As New StateObject&lt;br /&gt;        state.workSocket = client&lt;br /&gt;&lt;br /&gt;        ' Begin receiving the data from the remote device.&lt;br /&gt;        client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReceiveCallback), state)&lt;br /&gt;    End Sub 'Receive&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    Private Shared Sub ReceiveCallback(ByVal ar As IAsyncResult)&lt;br /&gt;&lt;br /&gt;        ' Retrieve the state object and the client socket &lt;br /&gt;        ' from the asynchronous state object.&lt;br /&gt;        Dim state As StateObject = CType(ar.AsyncState, StateObject)&lt;br /&gt;        Dim client As Socket = state.workSocket&lt;br /&gt;&lt;br /&gt;        ' Read data from the remote device.&lt;br /&gt;        Dim bytesRead As Integer = client.EndReceive(ar)&lt;br /&gt;&lt;br /&gt;        If bytesRead &amp;gt; 0 Then&lt;br /&gt;            ' There might be more data, so store the data received so far.&lt;br /&gt;            state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead))&lt;br /&gt;&lt;br /&gt;            ' Get the rest of the data.&lt;br /&gt;            client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReceiveCallback), state)&lt;br /&gt;        Else&lt;br /&gt;            ' All the data has arrived; put it in response.&lt;br /&gt;            If state.sb.Length &amp;gt; 1 Then&lt;br /&gt;                response = state.sb.ToString()&lt;br /&gt;            End If&lt;br /&gt;            ' Signal that all bytes have been received.&lt;br /&gt;            receiveDone.Set()&lt;br /&gt;        End If&lt;br /&gt;    End Sub 'ReceiveCallback&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    Private Shared Sub Send(ByVal client As Socket, ByVal data As String)&lt;br /&gt;        ' Convert the string data to byte data using ASCII encoding.&lt;br /&gt;        Dim byteData As Byte() = Encoding.ASCII.GetBytes(data)&lt;br /&gt;&lt;br /&gt;        ' Begin sending the data to the remote device.&lt;br /&gt;        client.BeginSend(byteData, 0, byteData.Length, 0, New AsyncCallback(AddressOf SendCallback), client)&lt;br /&gt;    End Sub 'Send&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    Private Shared Sub SendCallback(ByVal ar As IAsyncResult)&lt;br /&gt;        ' Retrieve the socket from the state object.&lt;br /&gt;        Dim client As Socket = CType(ar.AsyncState, Socket)&lt;br /&gt;&lt;br /&gt;        ' Complete sending the data to the remote device.&lt;br /&gt;        Dim bytesSent As Integer = client.EndSend(ar)&lt;br /&gt;        Console.WriteLine("Sent {0} bytes to server.", bytesSent)&lt;br /&gt;&lt;br /&gt;        ' Signal that all bytes have been sent.&lt;br /&gt;        sendDone.Set()&lt;br /&gt;    End Sub 'SendCallback&lt;br /&gt;End Class 'AsynchronousClient&lt;br /&gt;&lt;/eof&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For C#&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;using System;&lt;br /&gt;using System.Net;&lt;br /&gt;using System.Net.Sockets;&lt;br /&gt;using System.Threading;&lt;br /&gt;using System.Text;&lt;br /&gt;&lt;br /&gt;// State object for receiving data from remote device.&lt;br /&gt;public class StateObject {&lt;br /&gt;    // Client socket.&lt;br /&gt;    public Socket workSocket = null;&lt;br /&gt;    // Size of receive buffer.&lt;br /&gt;    public const int BufferSize = 256;&lt;br /&gt;    // Receive buffer.&lt;br /&gt;    public byte[] buffer = new byte[BufferSize];&lt;br /&gt;    // Received data string.&lt;br /&gt;    public StringBuilder sb = new StringBuilder();&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public class AsynchronousClient {&lt;br /&gt;    // The port number for the remote device.&lt;br /&gt;    private const int port = 11000;&lt;br /&gt;&lt;br /&gt;    // ManualResetEvent instances signal completion.&lt;br /&gt;    private static ManualResetEvent connectDone = &lt;br /&gt;        new ManualResetEvent(false);&lt;br /&gt;    private static ManualResetEvent sendDone = &lt;br /&gt;        new ManualResetEvent(false);&lt;br /&gt;    private static ManualResetEvent receiveDone = &lt;br /&gt;        new ManualResetEvent(false);&lt;br /&gt;&lt;br /&gt;    // The response from the remote device.&lt;br /&gt;    private static String response = String.Empty;&lt;br /&gt;&lt;br /&gt;    private static void StartClient() {&lt;br /&gt;        // Connect to a remote device.&lt;br /&gt;        try {&lt;br /&gt;            // Establish the remote endpoint for the socket.&lt;br /&gt;            // The name of the &lt;br /&gt;            // remote device is "host.contoso.com".&lt;br /&gt;            IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());&lt;br /&gt;            IPAddress ipAddress = ipHostInfo.AddressList[0];&lt;br /&gt;            IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);&lt;br /&gt;&lt;br /&gt;            // Create a TCP/IP socket.&lt;br /&gt;            Socket client = new Socket(AddressFamily.InterNetwork,&lt;br /&gt;                SocketType.Stream, ProtocolType.Tcp);&lt;br /&gt;&lt;br /&gt;            // Connect to the remote endpoint.&lt;br /&gt;            client.BeginConnect( remoteEP, &lt;br /&gt;                new AsyncCallback(ConnectCallback), client);&lt;br /&gt;            connectDone.WaitOne();&lt;br /&gt;&lt;br /&gt;            // Send test data to the remote device.&lt;br /&gt;            Send(client,"This is a test&lt;eof&gt;");&lt;br /&gt;            sendDone.WaitOne();&lt;br /&gt;&lt;br /&gt;            // Receive the response from the remote device.&lt;br /&gt;            Receive(client);&lt;br /&gt;            receiveDone.WaitOne();&lt;br /&gt;&lt;br /&gt;            // Write the response to the console.&lt;br /&gt;            Console.WriteLine("Response received : {0}", response);&lt;br /&gt;&lt;br /&gt;            // Release the socket.&lt;br /&gt;            client.Shutdown(SocketShutdown.Both);&lt;br /&gt;            client.Close();&lt;br /&gt;            &lt;br /&gt;        } catch (Exception e) {&lt;br /&gt;            Console.WriteLine(e.ToString());&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private static void ConnectCallback(IAsyncResult ar) {&lt;br /&gt;        try {&lt;br /&gt;            // Retrieve the socket from the state object.&lt;br /&gt;            Socket client = (Socket) ar.AsyncState;&lt;br /&gt;&lt;br /&gt;            // Complete the connection.&lt;br /&gt;            client.EndConnect(ar);&lt;br /&gt;&lt;br /&gt;            Console.WriteLine("Socket connected to {0}",&lt;br /&gt;                client.RemoteEndPoint.ToString());&lt;br /&gt;&lt;br /&gt;            // Signal that the connection has been made.&lt;br /&gt;            connectDone.Set();&lt;br /&gt;        } catch (Exception e) {&lt;br /&gt;            Console.WriteLine(e.ToString());&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private static void Receive(Socket client) {&lt;br /&gt;        try {&lt;br /&gt;            // Create the state object.&lt;br /&gt;            StateObject state = new StateObject();&lt;br /&gt;            state.workSocket = client;&lt;br /&gt;&lt;br /&gt;            // Begin receiving the data from the remote device.&lt;br /&gt;            client.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,&lt;br /&gt;                new AsyncCallback(ReceiveCallback), state);&lt;br /&gt;        } catch (Exception e) {&lt;br /&gt;            Console.WriteLine(e.ToString());&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private static void ReceiveCallback( IAsyncResult ar ) {&lt;br /&gt;        try {&lt;br /&gt;            // Retrieve the state object and the client socket &lt;br /&gt;            // from the asynchronous state object.&lt;br /&gt;            StateObject state = (StateObject) ar.AsyncState;&lt;br /&gt;            Socket client = state.workSocket;&lt;br /&gt;&lt;br /&gt;            // Read data from the remote device.&lt;br /&gt;            int bytesRead = client.EndReceive(ar);&lt;br /&gt;&lt;br /&gt;            if (bytesRead &amp;gt; 0) {&lt;br /&gt;                // There might be more data, so store the data received so far.&lt;br /&gt;            state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));&lt;br /&gt;&lt;br /&gt;                // Get the rest of the data.&lt;br /&gt;                client.BeginReceive(state.buffer,0,StateObject.BufferSize,0,&lt;br /&gt;                    new AsyncCallback(ReceiveCallback), state);&lt;br /&gt;            } else {&lt;br /&gt;                // All the data has arrived; put it in response.&lt;br /&gt;                if (state.sb.Length &amp;gt; 1) {&lt;br /&gt;                    response = state.sb.ToString();&lt;br /&gt;                }&lt;br /&gt;                // Signal that all bytes have been received.&lt;br /&gt;                receiveDone.Set();&lt;br /&gt;            }&lt;br /&gt;        } catch (Exception e) {&lt;br /&gt;            Console.WriteLine(e.ToString());&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private static void Send(Socket client, String data) {&lt;br /&gt;        // Convert the string data to byte data using ASCII encoding.&lt;br /&gt;        byte[] byteData = Encoding.ASCII.GetBytes(data);&lt;br /&gt;&lt;br /&gt;        // Begin sending the data to the remote device.&lt;br /&gt;        client.BeginSend(byteData, 0, byteData.Length, 0,&lt;br /&gt;            new AsyncCallback(SendCallback), client);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private static void SendCallback(IAsyncResult ar) {&lt;br /&gt;        try {&lt;br /&gt;            // Retrieve the socket from the state object.&lt;br /&gt;            Socket client = (Socket) ar.AsyncState;&lt;br /&gt;&lt;br /&gt;            // Complete sending the data to the remote device.&lt;br /&gt;            int bytesSent = client.EndSend(ar);&lt;br /&gt;            Console.WriteLine("Sent {0} bytes to server.", bytesSent);&lt;br /&gt;&lt;br /&gt;            // Signal that all bytes have been sent.&lt;br /&gt;            sendDone.Set();&lt;br /&gt;        } catch (Exception e) {&lt;br /&gt;            Console.WriteLine(e.ToString());&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;    &lt;br /&gt;    public static int Main(String[] args) {&lt;br /&gt;        StartClient();&lt;br /&gt;        return 0;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/eof&gt;&lt;/pre&gt;&lt;br /&gt;An asynchronous client socket does not suspend the application while waiting for network operations to complete. Instead, it uses the standard .NET Framework asynchronous programming model to process the network connection on one thread while the application continues to run on the original thread. Asynchronous sockets are appropriate for applications that make heavy use of the network or that cannot wait for network operations to complete before continuing.&lt;br /&gt;&lt;br /&gt;The Socket class follows the .NET Framework naming pattern for asynchronous methods; for example, the synchronous Receive method corresponds to the asynchronous BeginReceive and EndReceive methods.&lt;br /&gt;&lt;br /&gt;Asynchronous operations require a callback method to return the result of the operation. If your application does not need to know the result, then no callback method is required. The example code in this section demonstrates using a method to start connecting to a network device and a callback method to complete the connection, a method to start sending data and a callback method to complete the send, and a method to start receiving data and a callback method to end receiving data.&lt;br /&gt;&lt;br /&gt;Asynchronous sockets use multiple threads from the system thread pool to process network connections. One thread is responsible for initiating the sending or receiving of data; other threads complete the connection to the network device and send or receive the data. In the following examples, instances of the System.Threading.ManualResetEvent class are used to suspend execution of the main thread and signal when execution can continue.&lt;br /&gt;&lt;br /&gt;In the following example, to connect an asynchronous socket to a network device, the Connect method initializes a Socket and then calls the BeginConnect method, passing a remote endpoint that represents the network device, the connect callback method, and a state object (the client Socket), which is used to pass state information between asynchronous calls. The example implements the Connect method to connect the specified Socket to the specified endpoint. It assumes a global ManualResetEvent named connectDone.&lt;br /&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For VB&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;Public Shared Sub Connect(remoteEP As EndPoint, client As Socket)&lt;br /&gt;    client.BeginConnect(remoteEP, _&lt;br /&gt;       AddressOf ConnectCallback, client)&lt;br /&gt;    &lt;br /&gt;    connectDone.WaitOne()&lt;br /&gt;End Sub 'Connect&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For C#&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;public static void Connect(EndPoint remoteEP, Socket client) {&lt;br /&gt;    client.BeginConnect(remoteEP, &lt;br /&gt;        new AsyncCallback(ConnectCallback), client );&lt;br /&gt;&lt;br /&gt;   connectDone.WaitOne();&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The connect callback method ConnectCallback implements the AsyncCallback delegate. It connects to the remote device when the remote device is available and then signals the application thread that the connection is complete by setting the ManualResetEvent connectDone. The following code implements the ConnectCallback method.&lt;br /&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For VB&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;Private Shared Sub ConnectCallback(ar As IAsyncResult)&lt;br /&gt;    Try&lt;br /&gt;        ' Retrieve the socket from the state object.&lt;br /&gt;        Dim client As Socket = CType(ar.AsyncState, Socket)&lt;br /&gt;&lt;br /&gt;        ' Complete the connection.&lt;br /&gt;        client.EndConnect(ar)&lt;br /&gt;&lt;br /&gt;        Console.WriteLine("Socket connected to {0}", _&lt;br /&gt;            client.RemoteEndPoint.ToString())&lt;br /&gt;&lt;br /&gt;        ' Signal that the connection has been made.&lt;br /&gt;        connectDone.Set()&lt;br /&gt;    Catch e As Exception&lt;br /&gt;        Console.WriteLine(e.ToString())&lt;br /&gt;    End Try&lt;br /&gt;End Sub 'ConnectCallback&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For C#&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;private static void ConnectCallback(IAsyncResult ar) {&lt;br /&gt;    try {&lt;br /&gt;        // Retrieve the socket from the state object.&lt;br /&gt;        Socket client = (Socket) ar.AsyncState;&lt;br /&gt;&lt;br /&gt;        // Complete the connection.&lt;br /&gt;        client.EndConnect(ar);&lt;br /&gt;&lt;br /&gt;        Console.WriteLine("Socket connected to {0}",&lt;br /&gt;            client.RemoteEndPoint.ToString());&lt;br /&gt;&lt;br /&gt;        // Signal that the connection has been made.&lt;br /&gt;        connectDone.Set();&lt;br /&gt;    } catch (Exception e) {&lt;br /&gt;        Console.WriteLine(e.ToString());&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The example method Send encodes the specified string data in ASCII format and sends it asynchronously to the network device represented by the specified socket. The following example implements the Send method.&lt;br /&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For VB&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;Private Shared Sub Send(client As Socket, data As [String])&lt;br /&gt;    ' Convert the string data to byte data using ASCII encoding.&lt;br /&gt;    Dim byteData As Byte() = Encoding.ASCII.GetBytes(data)&lt;br /&gt;&lt;br /&gt;    ' Begin sending the data to the remote device.&lt;br /&gt;    client.BeginSend(byteData, 0, byteData.Length, SocketFlags.None, _&lt;br /&gt;        AddressOf SendCallback, client)&lt;br /&gt;End Sub 'Send&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For C#&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;private static void Send(Socket client, String data) {&lt;br /&gt;    // Convert the string data to byte data using ASCII encoding.&lt;br /&gt;    byte[] byteData = Encoding.ASCII.GetBytes(data);&lt;br /&gt;&lt;br /&gt;    // Begin sending the data to the remote device.&lt;br /&gt;    client.BeginSend(byteData, 0, byteData.Length, SocketFlags.None,&lt;br /&gt;        new AsyncCallback(SendCallback), client);&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The send callback method SendCallback implements the AsyncCallback delegate. It sends the data when the network device is ready to receive. The following example shows the implementation of the SendCallback method. It assumes a global ManualResetEvent named sendDone.&lt;br /&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For VB&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;Private Shared Sub SendCallback(ar As IAsyncResult)&lt;br /&gt;    Try&lt;br /&gt;        ' Retrieve the socket from the state object.&lt;br /&gt;        Dim client As Socket = CType(ar.AsyncState, Socket)&lt;br /&gt;&lt;br /&gt;        ' Complete sending the data to the remote device.&lt;br /&gt;        Dim bytesSent As Integer = client.EndSend(ar)&lt;br /&gt;        Console.WriteLine("Sent {0} bytes to server.", bytesSent)&lt;br /&gt;&lt;br /&gt;        ' Signal that all bytes have been sent.&lt;br /&gt;        sendDone.Set()&lt;br /&gt;    Catch e As Exception&lt;br /&gt;        Console.WriteLine(e.ToString())&lt;br /&gt;    End Try&lt;br /&gt;End Sub 'SendCallback&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For C#&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;private static void SendCallback(IAsyncResult ar) {&lt;br /&gt;    try {&lt;br /&gt;        // Retrieve the socket from the state object.&lt;br /&gt;        Socket client = (Socket) ar.AsyncState;&lt;br /&gt;&lt;br /&gt;        // Complete sending the data to the remote device.&lt;br /&gt;        int bytesSent = client.EndSend(ar);&lt;br /&gt;        Console.WriteLine("Sent {0} bytes to server.", bytesSent);&lt;br /&gt;&lt;br /&gt;        // Signal that all bytes have been sent.&lt;br /&gt;        sendDone.Set();&lt;br /&gt;    } catch (Exception e) {&lt;br /&gt;        Console.WriteLine(e.ToString());&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Reading data from a client socket requires a state object that passes values between asynchronous calls. The following class is an example state object for receiving data from a client socket. It contains a field for the client socket, a buffer for the received data, and a StringBuilder to hold the incoming data string. Placing these fields in the state object allows their values to be preserved across multiple calls to read data from the client socket.&lt;br /&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For VB&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;Public Class StateObject&lt;br /&gt;    ' Client socket.&lt;br /&gt;    Public workSocket As Socket = Nothing &lt;br /&gt;    ' Size of receive buffer.&lt;br /&gt;    Public BufferSize As Integer = 256&lt;br /&gt;    ' Receive buffer.&lt;br /&gt;    Public buffer(256) As Byte &lt;br /&gt;    ' Received data string.&lt;br /&gt;    Public sb As New StringBuilder()&lt;br /&gt;End Class 'StateObject&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For C#&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;public class StateObject {&lt;br /&gt;    // Client socket.&lt;br /&gt;    public Socket workSocket = null;&lt;br /&gt;    // Size of receive buffer.&lt;br /&gt;    public const int BufferSize = 256;&lt;br /&gt;    // Receive buffer.&lt;br /&gt;    public byte[] buffer = new byte[BufferSize];&lt;br /&gt;    // Received data string.&lt;br /&gt;    public StringBuilder sb = new StringBuilder();&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The example Receive method sets up the state object and then calls the BeginReceive method to read the data from the client socket asynchronously. The following example implements the Receive method.&lt;br /&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For VB&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;Private Shared Sub Receive(client As Socket)&lt;br /&gt;    Try&lt;br /&gt;        ' Create the state object.&lt;br /&gt;        Dim state As New StateObject()&lt;br /&gt;        state.workSocket = client&lt;br /&gt;            &lt;br /&gt;        ' Begin receiving the data from the remote device.&lt;br /&gt;        client.BeginReceive(state.buffer, 0, state.BufferSize, 0, _&lt;br /&gt;            AddressOf ReceiveCallback, state)&lt;br /&gt;    Catch e As Exception&lt;br /&gt;        Console.WriteLine(e.ToString())&lt;br /&gt;    End Try&lt;br /&gt;End Sub 'Receive&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For C#&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;private static void Receive(Socket client) {&lt;br /&gt;    try {&lt;br /&gt;        // Create the state object.&lt;br /&gt;        StateObject state = new StateObject();&lt;br /&gt;        state.workSocket = client;&lt;br /&gt;&lt;br /&gt;        // Begin receiving the data from the remote device.&lt;br /&gt;        client.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,&lt;br /&gt;            new AsyncCallback(ReceiveCallback), state);&lt;br /&gt;    } catch (Exception e) {&lt;br /&gt;        Console.WriteLine(e.ToString());&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The receive callback method ReceiveCallback implements the AsyncCallback delegate. It receives the data from the network device and builds a message string. It reads one or more bytes of data from the network into the data buffer and then calls the BeginReceive method again until the data sent by the client is complete. Once all the data is read from the client, ReceiveCallback signals the application thread that the data is complete by setting the ManualResetEvent sendDone.&lt;br /&gt;&lt;br /&gt;The following example code implements the ReceiveCallback method. It assumes a global string named response that holds the received string and a global ManualResetEvent named receiveDone. The server must shut down the client socket gracefully to end the network session.&lt;br /&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For VB&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;Private Shared Sub ReceiveCallback(ar As IAsyncResult)&lt;br /&gt;    Try&lt;br /&gt;        ' Retrieve the state object and the client socket &lt;br /&gt;        ' from the asynchronous state object.&lt;br /&gt;        Dim state As StateObject = CType(ar.AsyncState, StateObject)&lt;br /&gt;        Dim client As Socket = state.workSocket&lt;br /&gt;&lt;br /&gt;        ' Read data from the remote device.&lt;br /&gt;        Dim bytesRead As Integer = client.EndReceive(ar)&lt;br /&gt;&lt;br /&gt;        If bytesRead &amp;gt; 0 Then&lt;br /&gt;            ' There might be more data, so store the data received so far.&lt;br /&gt;            state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, _&lt;br /&gt;                bytesRead))&lt;br /&gt;&lt;br /&gt;            '  Get the rest of the data.&lt;br /&gt;            client.BeginReceive(state.buffer, 0, state.BufferSize, 0, _&lt;br /&gt;                AddressOf ReceiveCallback, state)&lt;br /&gt;        Else&lt;br /&gt;            ' All the data has arrived; put it in response.&lt;br /&gt;            If state.sb.Length &amp;gt; 1 Then&lt;br /&gt;                response = state.sb.ToString()&lt;br /&gt;            End If&lt;br /&gt;            ' Signal that all bytes have been received.&lt;br /&gt;            receiveDone.Set()&lt;br /&gt;        End If&lt;br /&gt;    Catch e As Exception&lt;br /&gt;        Console.WriteLine(e.ToString())&lt;br /&gt;    End Try&lt;br /&gt;End Sub 'ReceiveCallback&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For C#&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;private static void ReceiveCallback( IAsyncResult ar ) {&lt;br /&gt;    try {&lt;br /&gt;        // Retrieve the state object and the client socket &lt;br /&gt;        // from the asynchronous state object.&lt;br /&gt;        StateObject state = (StateObject) ar.AsyncState;&lt;br /&gt;        Socket client = state.workSocket;&lt;br /&gt;        // Read data from the remote device.&lt;br /&gt;        int bytesRead = client.EndReceive(ar);&lt;br /&gt;        if (bytesRead &amp;gt; 0) {&lt;br /&gt;            // There might be more data, so store the data received so far.&lt;br /&gt;            state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));&lt;br /&gt;                //  Get the rest of the data.&lt;br /&gt;            client.BeginReceive(state.buffer,0,StateObject.BufferSize,0,&lt;br /&gt;                new AsyncCallback(ReceiveCallback), state);&lt;br /&gt;        } else {&lt;br /&gt;            // All the data has arrived; put it in response.&lt;br /&gt;            if (state.sb.Length &amp;gt; 1) {&lt;br /&gt;                response = state.sb.ToString();&lt;br /&gt;            }&lt;br /&gt;            // Signal that all bytes have been received.&lt;br /&gt;            receiveDone.Set();&lt;br /&gt;        }&lt;br /&gt;    } catch (Exception e) {&lt;br /&gt;        Console.WriteLine(e.ToString());&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Download project and code &lt;a href="http://www.ziddu.com/download/14698067/asynchronous_client_server_net.rar.html"&gt;here&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6709431659636147588-34977471967274617?l=www.myg3nx.co.cc' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.myg3nx.co.cc/feeds/34977471967274617/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.myg3nx.co.cc/2011/04/tutorial-asynchronous-socket.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6709431659636147588/posts/default/34977471967274617'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6709431659636147588/posts/default/34977471967274617'/><link rel='alternate' type='text/html' href='http://www.myg3nx.co.cc/2011/04/tutorial-asynchronous-socket.html' title='Tutorial Asynchronous Socket Programming using .NET (For Client)'/><author><name>haries</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6709431659636147588.post-882282603119873853</id><published>2011-04-21T23:15:00.000-07:00</published><updated>2011-04-21T23:16:26.429-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='server'/><category scheme='http://www.blogger.com/atom/ns#' term='java'/><category scheme='http://www.blogger.com/atom/ns#' term='socket'/><category scheme='http://www.blogger.com/atom/ns#' term='synchronous'/><title type='text'>Tutorial Synchronous Socket Programming using JAVA (For Server)</title><content type='html'>When you have setup code for client application, after a connection is established, a server application uses the same kind of Socket object for its side of the communications. However, to accept a connection from a client, it must first create a ServerSocket, bound to the correct port. Let's recreate the previous conversation from the server's point of view:&lt;br /&gt;&lt;br /&gt;&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;// Meanwhile, on foo.bar.com...&lt;br /&gt;    try {&lt;br /&gt;        ServerSocket listener = new ServerSocket( 1234 );&lt;br /&gt;&lt;br /&gt;        while ( !finished ) {&lt;br /&gt;            Socket client = listener.accept( );  // wait for connection&lt;br /&gt;&lt;br /&gt;            InputStream in = client.getInputStream(  );&lt;br /&gt;            OutputStream out = client.getOutputStream(  );&lt;br /&gt;&lt;br /&gt;            // read a byte&lt;br /&gt;            byte someByte = (byte)in.read(  );&lt;br /&gt;&lt;br /&gt;            // read a newline or carriage-return-delimited string&lt;br /&gt;            BufferedReader bin =&lt;br /&gt;              new BufferedReader( new InputStreamReader( in ) );&lt;br /&gt;            String someString = bin.readLine( );&lt;br /&gt;&lt;br /&gt;            // write a byte&lt;br /&gt;            out.write(43);&lt;br /&gt;&lt;br /&gt;            // say goodbye&lt;br /&gt;            PrintWriter pout = new PrintWriter( out, true );&lt;br /&gt;            pout.println("Goodbye!");&lt;br /&gt;      &lt;br /&gt;            // read a serialized Java object&lt;br /&gt;            ObjectInputStream oin = new ObjectInputStream( in );&lt;br /&gt;            Date date = (Date)oin.readObject(  );&lt;br /&gt;&lt;br /&gt;            client.close(  );&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        listener.close(  );&lt;br /&gt;    }&lt;br /&gt;    catch (IOException e ) { ... }&lt;br /&gt;    catch (ClassNotFoundException e2 ) { ... }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;First, our server creates a ServerSocket attached to port 1234. On some systems, there are rules about what ports an application can use. Port numbers below 1024 are usually reserved for system processes and standard, well-known services, so we pick a port number outside of this range. The ServerSocket is created only once; thereafter, we can accept as many connections as arrive.&lt;br /&gt;&lt;br /&gt;Next, we enter a loop, waiting for the accept( ) method of the ServerSocket to return an active Socket connection from a client. When a connection has been established, we perform the server side of our dialog, then close the connection and return to the top of the loop to wait for another connection. Finally, when the server application wants to stop listening for connections altogether, it calls the close( ) method of the ServerSocket.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6709431659636147588-882282603119873853?l=www.myg3nx.co.cc' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.myg3nx.co.cc/feeds/882282603119873853/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.myg3nx.co.cc/2011/04/tutorial-synchronous-socket-programming_7428.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6709431659636147588/posts/default/882282603119873853'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6709431659636147588/posts/default/882282603119873853'/><link rel='alternate' type='text/html' href='http://www.myg3nx.co.cc/2011/04/tutorial-synchronous-socket-programming_7428.html' title='Tutorial Synchronous Socket Programming using JAVA (For Server)'/><author><name>haries</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6709431659636147588.post-1177690250537845681</id><published>2011-04-21T23:13:00.000-07:00</published><updated>2011-04-21T23:13:55.991-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='java'/><category scheme='http://www.blogger.com/atom/ns#' term='socket'/><category scheme='http://www.blogger.com/atom/ns#' term='synchronous'/><category scheme='http://www.blogger.com/atom/ns#' term='client'/><title type='text'>Tutorial Synchronous Socket Programming using JAVA (For Client)</title><content type='html'>A client application opens a connection to a server by constructing a Socket that specifies the hostname and port number of the desired server:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;try {&lt;br /&gt;        Socket sock = new Socket("wupost.wustl.edu", 25);&lt;br /&gt;    } catch ( UnknownHostException e ) {&lt;br /&gt;        System.out.println("Can't find host.");&lt;br /&gt;    } catch ( IOException e ) {&lt;br /&gt;        System.out.println("Error connecting to host.");&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;This code fragment attempts to connect a Socket to port 25 (the SMTP mail service) of the host wupost.wustl.edu. The client handles the possibility that the hostname can't be resolved (UnknownHostException) and that it might not be able to connect to it (IOException). The constructor can also accept a string containing the host's IP address:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;Socket sock = new Socket("22.66.89.167", 25);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Once a connection is made, input and output streams can be retrieved with the Socket getInputStream( ) and getOutputStream( ) methods. The following (rather arbitrary) code sends and receives some data with the streams:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;try {&lt;br /&gt;        Socket server = new Socket("foo.bar.com", 1234);&lt;br /&gt;        InputStream in = server.getInputStream( );&lt;br /&gt;        OutputStream out = server.getOutputStream( );&lt;br /&gt;&lt;br /&gt;        // write a byte&lt;br /&gt;        out.write(42);&lt;br /&gt;&lt;br /&gt;        // write a newline or carriage return delimited string&lt;br /&gt;        PrintWriter pout = new PrintWriter( out, true );&lt;br /&gt;        pout.println("Hello!");&lt;br /&gt;&lt;br /&gt;        // read a byte&lt;br /&gt;        byte back = (byte)in.read( );&lt;br /&gt;&lt;br /&gt;        // read a newline or carriage return delimited string&lt;br /&gt;        BufferedReader bin =&lt;br /&gt;          new BufferedReader( new InputStreamReader( in ) );&lt;br /&gt;        String response = bin.readLine( );&lt;br /&gt;&lt;br /&gt;        // send a serialized Java object&lt;br /&gt;        ObjectOutputStream oout = new&lt;br /&gt;        ObjectOutputStream( out );&lt;br /&gt;        oout.writeObject( new java.util.Date( ) );&lt;br /&gt;        oout.flush( );&lt;br /&gt;      &lt;br /&gt;        server.close( );&lt;br /&gt;    }&lt;br /&gt;    catch (IOException e ) { ... }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;In this exchange, the client first creates a Socket for communicating with the server. The Socket constructor specifies the server's hostname (foo.bar.com) and a prearranged port number (1234). Once the connection is established, the client writes a single byte to the server using the OutputStream's write( ) method. To send a string of text more easily, it then wraps a PrintWriter around the OutputStream. Next, it performs the complementary operations: reading a byte from the server using InputStream's read( ) method and then creating a BufferedReader from which to get a full string of text. Finally, we do something really funky and send a serialized Java object to the server, using an ObjectOutputStream.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6709431659636147588-1177690250537845681?l=www.myg3nx.co.cc' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.myg3nx.co.cc/feeds/1177690250537845681/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.myg3nx.co.cc/2011/04/tutorial-synchronous-socket-programming_6527.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6709431659636147588/posts/default/1177690250537845681'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6709431659636147588/posts/default/1177690250537845681'/><link rel='alternate' type='text/html' href='http://www.myg3nx.co.cc/2011/04/tutorial-synchronous-socket-programming_6527.html' title='Tutorial Synchronous Socket Programming using JAVA (For Client)'/><author><name>haries</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6709431659636147588.post-8490065719932500865</id><published>2011-04-21T23:04:00.000-07:00</published><updated>2011-04-21T23:07:46.627-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='server'/><category scheme='http://www.blogger.com/atom/ns#' term='socket'/><category scheme='http://www.blogger.com/atom/ns#' term='synchronous'/><category scheme='http://www.blogger.com/atom/ns#' term='dotnet'/><title type='text'>Tutorial Synchronous Socket Programming using .NET (For Server)</title><content type='html'>The following example program creates a server that receives connection requests from clients. The server is built with a synchronous socket, so execution of the server application is suspended while it waits for a connection from a client. The application receives a string from the client, displays the string on the console, and then echoes the string back to the client. The string from the client must contain the string "&amp;lt;EOF&amp;gt;" to signal the end of the message.&lt;br /&gt;&lt;br /&gt;&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For VB&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;Imports System&lt;br /&gt;Imports System.Net&lt;br /&gt;Imports System.Net.Sockets&lt;br /&gt;Imports System.Text&lt;br /&gt;Imports Microsoft.VisualBasic&lt;br /&gt;&lt;br /&gt;Public Class SynchronousSocketListener&lt;br /&gt;&lt;br /&gt;    ' Incoming data from the client.&lt;br /&gt;    Public Shared data As String = Nothing&lt;br /&gt;&lt;br /&gt;    Public Shared Sub Main()&lt;br /&gt;        ' Data buffer for incoming data.&lt;br /&gt;        Dim bytes() As Byte = New [Byte](1024) {}&lt;br /&gt;&lt;br /&gt;        ' Establish the local endpoint for the socket.&lt;br /&gt;        ' Dns.GetHostName returns the name of the &lt;br /&gt;        ' host running the application.&lt;br /&gt;        Dim ipHostInfo As IPHostEntry = Dns.Resolve(Dns.GetHostName())&lt;br /&gt;        Dim ipAddress As IPAddress = ipHostInfo.AddressList(0)&lt;br /&gt;        Dim localEndPoint As New IPEndPoint(ipAddress, 11000)&lt;br /&gt;&lt;br /&gt;        ' Create a TCP/IP socket.&lt;br /&gt;        Dim listener As New Socket(AddressFamily.InterNetwork, _&lt;br /&gt;            SocketType.Stream, ProtocolType.Tcp)&lt;br /&gt;&lt;br /&gt;        ' Bind the socket to the local endpoint and &lt;br /&gt;        ' listen for incoming connections.&lt;br /&gt;&lt;br /&gt;        listener.Bind(localEndPoint)&lt;br /&gt;        listener.Listen(10)&lt;br /&gt;&lt;br /&gt;        ' Start listening for connections.&lt;br /&gt;        While True&lt;br /&gt;            Console.WriteLine("Waiting for a connection...")&lt;br /&gt;            ' Program is suspended while waiting for an incoming connection.&lt;br /&gt;            Dim handler As Socket = listener.Accept()&lt;br /&gt;            data = Nothing&lt;br /&gt;&lt;br /&gt;            ' An incoming connection needs to be processed.&lt;br /&gt;            While True&lt;br /&gt;                bytes = New Byte(1024) {}&lt;br /&gt;                Dim bytesRec As Integer = handler.Receive(bytes)&lt;br /&gt;                data += Encoding.ASCII.GetString(bytes, 0, bytesRec)&lt;br /&gt;                If data.IndexOf("&lt;eof&gt;&amp;lt;EOF&amp;gt;") &amp;gt; -1 Then&lt;br /&gt;                    Exit While&lt;br /&gt;                End If&lt;br /&gt;            End While&lt;br /&gt;            ' Show the data on the console.&lt;br /&gt;            Console.WriteLine("Text received : {0}", data)&lt;br /&gt;            ' Echo the data back to the client.&lt;br /&gt;            Dim msg As Byte() = Encoding.ASCII.GetBytes(data)&lt;br /&gt;            handler.Send(msg)&lt;br /&gt;            handler.Shutdown(SocketShutdown.Both)&lt;br /&gt;            handler.Close()&lt;br /&gt;        End While&lt;br /&gt;    End Sub&lt;br /&gt;&lt;br /&gt;End Class 'SynchronousSocketListener&lt;br /&gt;&lt;/eof&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For C#&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;using System;&lt;br /&gt;using System.Net;&lt;br /&gt;using System.Net.Sockets;&lt;br /&gt;using System.Text;&lt;br /&gt;&lt;br /&gt;public class SynchronousSocketListener {&lt;br /&gt;    &lt;br /&gt;    // Incoming data from the client.&lt;br /&gt;    public static string data = null;&lt;br /&gt;&lt;br /&gt;    public static void StartListening() {&lt;br /&gt;        // Data buffer for incoming data.&lt;br /&gt;        byte[] bytes = new Byte[1024];&lt;br /&gt;&lt;br /&gt;        // Establish the local endpoint for the socket.&lt;br /&gt;        // Dns.GetHostName returns the name of the &lt;br /&gt;        // host running the application.&lt;br /&gt;        IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());&lt;br /&gt;        IPAddress ipAddress = ipHostInfo.AddressList[0];&lt;br /&gt;        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);&lt;br /&gt;&lt;br /&gt;        // Create a TCP/IP socket.&lt;br /&gt;        Socket listener = new Socket(AddressFamily.InterNetwork,&lt;br /&gt;            SocketType.Stream, ProtocolType.Tcp );&lt;br /&gt;&lt;br /&gt;        // Bind the socket to the local endpoint and &lt;br /&gt;        // listen for incoming connections.&lt;br /&gt;        try {&lt;br /&gt;            listener.Bind(localEndPoint);&lt;br /&gt;            listener.Listen(10);&lt;br /&gt;&lt;br /&gt;            // Start listening for connections.&lt;br /&gt;            while (true) {&lt;br /&gt;                Console.WriteLine("Waiting for a connection...");&lt;br /&gt;                // Program is suspended while waiting for an incoming connection.&lt;br /&gt;                Socket handler = listener.Accept();&lt;br /&gt;                data = null;&lt;br /&gt;&lt;br /&gt;                // An incoming connection needs to be processed.&lt;br /&gt;                while (true) {&lt;br /&gt;                    bytes = new byte[1024];&lt;br /&gt;                    int bytesRec = handler.Receive(bytes);&lt;br /&gt;                    data += Encoding.ASCII.GetString(bytes,0,bytesRec);&lt;br /&gt;                    if (data.IndexOf("&lt;eof&gt;&amp;lt;EOF&amp;gt;") &amp;gt; -1) {&lt;br /&gt;                        break;&lt;br /&gt;                    }&lt;br /&gt;                }&lt;br /&gt;&lt;br /&gt;                // Show the data on the console.&lt;br /&gt;                Console.WriteLine( "Text received : {0}", data);&lt;br /&gt;&lt;br /&gt;                // Echo the data back to the client.&lt;br /&gt;                byte[] msg = Encoding.ASCII.GetBytes(data);&lt;br /&gt;&lt;br /&gt;                handler.Send(msg);&lt;br /&gt;                handler.Shutdown(SocketShutdown.Both);&lt;br /&gt;                handler.Close();&lt;br /&gt;            }&lt;br /&gt;            &lt;br /&gt;        } catch (Exception e) {&lt;br /&gt;            Console.WriteLine(e.ToString());&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        Console.WriteLine("\nPress ENTER to continue...");&lt;br /&gt;        Console.Read();&lt;br /&gt;        &lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public static int Main(String[] args) {&lt;br /&gt;        StartListening();&lt;br /&gt;        return 0;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/eof&gt;&lt;/pre&gt;&lt;br /&gt;Synchronous server sockets suspend the execution of the application until a connection request is received on the socket. Synchronous server sockets are not suitable for applications that make heavy use of the network in their operation, but they can be suitable for simple network applications.&lt;br /&gt;&lt;br /&gt;After a Socket is set to listen on an endpoint using the Bind and Listen methods, it is ready to accept incoming connection requests using the Accept method. The application is suspended until a connection request is received when the Accept method is called.&lt;br /&gt;&lt;br /&gt;When a connection request is received, Accept returns a new Socket instance that is associated with the connecting client. The following example reads data from the client, displays it on the console, and echoes the data back to the client. The Socket does not specify any messaging protocol, so the string "&lt;eof&gt;" marks the end of the message data. It assumes that a Socket named listener has been initialized and bound to an endpoint.&lt;br /&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For VB&lt;/span&gt;&lt;br /&gt;&lt;/eof&gt;&lt;br /&gt;&lt;pre&gt;Console.WriteLine("Waiting for a connection...")&lt;br /&gt;Dim handler As Socket = listener.Accept()&lt;br /&gt;Dim data As String = Nothing&lt;br /&gt;            &lt;br /&gt;While True&lt;br /&gt;    bytes = New Byte(1024) {}&lt;br /&gt;    Dim bytesRec As Integer = handler.Receive(bytes)&lt;br /&gt;    data += Encoding.ASCII.GetString(bytes, 0, bytesRec)&lt;br /&gt;    If data.IndexOf("&lt;eof&gt;&amp;lt;EOF&amp;gt;") &amp;gt; - 1 Then&lt;br /&gt;        Exit While&lt;br /&gt;    End If&lt;br /&gt;End While&lt;br /&gt;            &lt;br /&gt;Console.WriteLine("Text received : {0}", data)&lt;br /&gt;&lt;br /&gt;Dim msg As Byte() = Encoding.ASCII.GetBytes(data)&lt;br /&gt;handler.Send(msg)&lt;br /&gt;handler.Shutdown(SocketShutdown.Both)&lt;br /&gt;handler.Close()&lt;br /&gt;&lt;/eof&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For C#&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;Console.WriteLine("Waiting for a connection...");&lt;br /&gt;Socket handler = listener.Accept();&lt;br /&gt;String data = null;&lt;br /&gt;&lt;br /&gt;while (true) {&lt;br /&gt;    bytes = new byte[1024];&lt;br /&gt;    int bytesRec = handler.Receive(bytes);&lt;br /&gt;    data += Encoding.ASCII.GetString(bytes,0,bytesRec);&lt;br /&gt;    if (data.IndexOf("&lt;eof&gt;&amp;lt;EOF&amp;gt;") &amp;gt; -1) {&lt;br /&gt;        break;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;Console.WriteLine( "Text received : {0}", data);&lt;br /&gt;&lt;br /&gt;byte[] msg = Encoding.ASCII.GetBytes(data);&lt;br /&gt;handler.Send(msg);&lt;br /&gt;handler.Shutdown(SocketShutdown.Both);&lt;br /&gt;handler.Close();&lt;br /&gt;&lt;/eof&gt;&lt;/pre&gt;&lt;br /&gt;Download project and code &lt;a href="http://www.ziddu.com/download/14698027/synchronous_client_server_net.rar.html"&gt;here&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6709431659636147588-8490065719932500865?l=www.myg3nx.co.cc' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.myg3nx.co.cc/feeds/8490065719932500865/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.myg3nx.co.cc/2011/04/tutorial-synchronous-socket-programming_21.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6709431659636147588/posts/default/8490065719932500865'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6709431659636147588/posts/default/8490065719932500865'/><link rel='alternate' type='text/html' href='http://www.myg3nx.co.cc/2011/04/tutorial-synchronous-socket-programming_21.html' title='Tutorial Synchronous Socket Programming using .NET (For Server)'/><author><name>haries</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6709431659636147588.post-6124642702540619206</id><published>2011-04-20T22:28:00.000-07:00</published><updated>2011-04-21T23:08:57.630-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='program'/><category scheme='http://www.blogger.com/atom/ns#' term='socket'/><category scheme='http://www.blogger.com/atom/ns#' term='synchronous'/><category scheme='http://www.blogger.com/atom/ns#' term='dotnet'/><title type='text'>Tutorial Synchronous Socket Programming using .NET (For Client)</title><content type='html'>The following example program creates a client that connects to a server. The client is built with a synchronous socket, so execution of the client application is suspended until the server returns a response. The application sends a string to the server and then displays the string returned by the server on the console.&lt;br /&gt;&lt;a name='more'&gt;&lt;/a&gt;&lt;pre&gt;&lt;span style="color: lime;"&gt;CODE FOR VB&lt;/span&gt;&lt;/pre&gt;&lt;pre&gt;Imports System&lt;br /&gt;Imports System.Net&lt;br /&gt;Imports System.Net.Sockets&lt;br /&gt;Imports System.Text&lt;br /&gt;&lt;br /&gt;Public Class SynchronousSocketClient&lt;br /&gt;&lt;br /&gt;    Public Shared Sub Main()&lt;br /&gt;        ' Data buffer for incoming data.&lt;br /&gt;        Dim bytes(1024) As Byte&lt;br /&gt;&lt;br /&gt;        ' Connect to a remote device.&lt;br /&gt;&lt;br /&gt;        ' Establish the remote endpoint for the socket.&lt;br /&gt;        ' This example uses port 11000 on the local computer.&lt;br /&gt;        Dim ipHostInfo As IPHostEntry = Dns.Resolve(Dns.GetHostName())&lt;br /&gt;        Dim ipAddress As IPAddress = ipHostInfo.AddressList(0)&lt;br /&gt;        Dim remoteEP As New IPEndPoint(ipAddress, 11000)&lt;br /&gt;&lt;br /&gt;        ' Create a TCP/IP socket.&lt;br /&gt;        Dim sender As New Socket(AddressFamily.InterNetwork, _&lt;br /&gt;            SocketType.Stream, ProtocolType.Tcp)&lt;br /&gt;&lt;br /&gt;        ' Connect the socket to the remote endpoint.&lt;br /&gt;        sender.Connect(remoteEP)&lt;br /&gt;&lt;br /&gt;        Console.WriteLine("Socket connected to {0}", _&lt;br /&gt;            sender.RemoteEndPoint.ToString())&lt;br /&gt;&lt;br /&gt;        ' Encode the data string into a byte array.&lt;br /&gt;        Dim msg As Byte() = _&lt;br /&gt;            Encoding.ASCII.GetBytes("This is a test&amp;lt;EOF&amp;gt;&lt;eof&gt;")&lt;br /&gt;&lt;br /&gt;        ' Send the data through the socket.&lt;br /&gt;        Dim bytesSent As Integer = sender.Send(msg)&lt;br /&gt;&lt;br /&gt;        ' Receive the response from the remote device.&lt;br /&gt;        Dim bytesRec As Integer = sender.Receive(bytes)&lt;br /&gt;        Console.WriteLine("Echoed test = {0}", _&lt;br /&gt;            Encoding.ASCII.GetString(bytes, 0, bytesRec))&lt;br /&gt;&lt;br /&gt;        ' Release the socket.&lt;br /&gt;        sender.Shutdown(SocketShutdown.Both)&lt;br /&gt;        sender.Close()&lt;br /&gt;    End Sub&lt;br /&gt;&lt;br /&gt;End Class 'SynchronousSocketClient&amp;nbsp; &lt;/eof&gt;&lt;/pre&gt;&lt;br /&gt;&lt;pre&gt;&lt;span style="color: lime;"&gt;CODE FOR C#&lt;/span&gt;&lt;/pre&gt;&lt;pre&gt;using System;&lt;br /&gt;using System.Net;&lt;br /&gt;using System.Net.Sockets;&lt;br /&gt;using System.Text;&lt;br /&gt;&lt;br /&gt;public class SynchronousSocketClient {&lt;br /&gt;&lt;br /&gt;    public static void StartClient() {&lt;br /&gt;        // Data buffer for incoming data.&lt;br /&gt;        byte[] bytes = new byte[1024];&lt;br /&gt;&lt;br /&gt;        // Connect to a remote device.&lt;br /&gt;        try {&lt;br /&gt;            // Establish the remote endpoint for the socket.&lt;br /&gt;            // This example uses port 11000 on the local computer.&lt;br /&gt;            IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());&lt;br /&gt;            IPAddress ipAddress = ipHostInfo.AddressList[0];&lt;br /&gt;            IPEndPoint remoteEP = new IPEndPoint(ipAddress,11000);&lt;br /&gt;&lt;br /&gt;            // Create a TCP/IP  socket.&lt;br /&gt;            Socket sender = new Socket(AddressFamily.InterNetwork, &lt;br /&gt;                SocketType.Stream, ProtocolType.Tcp );&lt;br /&gt;&lt;br /&gt;            // Connect the socket to the remote endpoint. Catch any errors.&lt;br /&gt;            try {&lt;br /&gt;                sender.Connect(remoteEP);&lt;br /&gt;&lt;br /&gt;                Console.WriteLine("Socket connected to {0}",&lt;br /&gt;                    sender.RemoteEndPoint.ToString());&lt;br /&gt;&lt;br /&gt;                // Encode the data string into a byte array.&lt;br /&gt;                byte[] msg = Encoding.ASCII.GetBytes("This is a test&amp;lt;EOF&amp;gt;&lt;eof&gt;");&lt;br /&gt;&lt;br /&gt;                // Send the data through the socket.&lt;br /&gt;                int bytesSent = sender.Send(msg);&lt;br /&gt;&lt;br /&gt;                // Receive the response from the remote device.&lt;br /&gt;                int bytesRec = sender.Receive(bytes);&lt;br /&gt;                Console.WriteLine("Echoed test = {0}",&lt;br /&gt;                    Encoding.ASCII.GetString(bytes,0,bytesRec));&lt;br /&gt;&lt;br /&gt;                // Release the socket.&lt;br /&gt;                sender.Shutdown(SocketShutdown.Both);&lt;br /&gt;                sender.Close();&lt;br /&gt;                &lt;br /&gt;            } catch (ArgumentNullException ane) {&lt;br /&gt;                Console.WriteLine("ArgumentNullException : {0}",ane.ToString());&lt;br /&gt;            } catch (SocketException se) {&lt;br /&gt;                Console.WriteLine("SocketException : {0}",se.ToString());&lt;br /&gt;            } catch (Exception e) {&lt;br /&gt;                Console.WriteLine("Unexpected exception : {0}", e.ToString());&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;        } catch (Exception e) {&lt;br /&gt;            Console.WriteLine( e.ToString());&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;    &lt;br /&gt;    public static int Main(String[] args) {&lt;br /&gt;        StartClient();&lt;br /&gt;        return 0;&lt;br /&gt;    }&lt;br /&gt;}&amp;nbsp;&lt;/eof&gt;&lt;/pre&gt;&lt;br /&gt;A synchronous client socket suspends the application program while the network operation completes. Synchronous sockets are not suitable for applications that make heavy use of the network for their operation, but they can enable simple access to network services for other applications.&lt;br /&gt;&lt;br /&gt;To send data, pass a byte array to one of the Socket class's send-data methods (Send and SendTo). The following example encodes a string into a byte array buffer using the Encoding.ASCII property and then transmits the buffer to the network device using the Send method. The Send method returns the number of bytes sent to the network device.&lt;br /&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For VB &lt;/span&gt;&lt;br /&gt;&lt;pre&gt;Dim msg As Byte() = _&lt;br /&gt;    System.Text.Encoding.ASCII.GetBytes("This is a test&amp;lt;EOF&amp;gt;")&lt;br /&gt;Dim bytesSent As Integer = s.Send(msg)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For C# &lt;/span&gt;&lt;br /&gt;&lt;pre&gt;byte[] msg = System.Text.Encoding.ASCII.GetBytes("This is a test&amp;lt;EOF&amp;gt;");&lt;br /&gt;int bytesSent = s.Send(msg);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The Send method removes the bytes from the buffer and queues them with the network interface to be sent to the network device. The network interface might not send the data immediately, but it will send it eventually, as long as the connection is closed normally with the Shutdown method.&lt;br /&gt;&lt;br /&gt;To receive data from a network device, pass a buffer to one of the Socket class's receive-data methods (Receive and ReceiveFrom). Synchronous sockets will suspend the application until bytes are received from the network or until the socket is closed. The following example receives data from the network and then displays it on the console. The example assumes that the data coming from the network is ASCII-encoded text. The Receive method returns the number of bytes received from the network.&lt;br /&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For VB &lt;/span&gt;&lt;br /&gt;&lt;pre&gt;Dim bytes(1024) As Byte&lt;br /&gt;Dim bytesRec = s.Receive(bytes)&lt;br /&gt;Console.WriteLine("Echoed text = {0}", _&lt;br /&gt;    System.Text.Encoding.ASCII.GetString(bytes, 0, bytesRec))&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For C# &lt;/span&gt;&lt;br /&gt;&lt;pre&gt;byte[] bytes = new byte[1024];&lt;br /&gt;int bytesRec = s.Receive(bytes);&lt;br /&gt;Console.WriteLine("Echoed text = {0}",&lt;br /&gt;    System.Text.Encoding.ASCII.GetString(bytes, 0, bytesRec));&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;When the socket is no longer needed, you need to release it by calling the Shutdown method and then calling the Close method. The following example releases a Socket. The SocketShutdown enumeration defines constants that indicate whether the socket should be closed for sending, for receiving, or for both.&lt;br /&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For VB &lt;/span&gt;&lt;br /&gt;&lt;pre&gt;s.Shutdown(SocketShutdown.Both)&lt;br /&gt;s.Close()&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="color: lime;"&gt;Code For C# &lt;/span&gt;&lt;br /&gt;&lt;pre&gt;s.Shutdown(SocketShutdown.Both);&lt;br /&gt;s.Close();&amp;nbsp;&lt;/pre&gt;&lt;br /&gt;Download project and demo &lt;a href="http://www.ziddu.com/download/14698027/synchronous_client_server_net.rar.html"&gt;here&lt;span id="goog_1544148071"&gt;&lt;/span&gt;&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6709431659636147588-6124642702540619206?l=www.myg3nx.co.cc' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.myg3nx.co.cc/feeds/6124642702540619206/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.myg3nx.co.cc/2011/04/tutorial-synchronous-socket-programming.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6709431659636147588/posts/default/6124642702540619206'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6709431659636147588/posts/default/6124642702540619206'/><link rel='alternate' type='text/html' href='http://www.myg3nx.co.cc/2011/04/tutorial-synchronous-socket-programming.html' title='Tutorial Synchronous Socket Programming using .NET (For Client)'/><author><name>haries</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6709431659636147588.post-4842002603766192789</id><published>2011-04-20T21:52:00.000-07:00</published><updated>2011-04-20T23:10:07.267-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='program'/><category scheme='http://www.blogger.com/atom/ns#' term='java'/><category scheme='http://www.blogger.com/atom/ns#' term='socket'/><category scheme='http://www.blogger.com/atom/ns#' term='tutorial'/><title type='text'>Basic Knowledge/Tutorial Programming About Socket in JAVA</title><content type='html'>The network is the soul of Java. Most of what is interesting about Java centers around the potential for dynamic, networked applications. As Java's networking APIs have matured, Java has also become the language of choice for implementing traditional client-server applications and services.&lt;br /&gt;&lt;br /&gt;The classes of java.net fall into two general categories: the Sockets API for working with low-level Internet protocols and higher-level, web-oriented APIs that work with uniform resource locators (URLs). Figure 1 shows the java.net package.&lt;br /&gt;&lt;br /&gt;&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Java's Sockets API provides access to the standard network protocols used for communications between hosts on the Internet. Sockets are the mechanism underlying all other kinds of portable networked communications. Sockets are the lowest-level toolyou can use sockets for any kind of communications between client and server or peer applications on the Net, but you have to implement your own application-level protocols for handling and interpreting the data. Higher-level networking tools, such as remote method invocation, HTTP, and web services are implemented on top of sockets.&lt;br /&gt;&lt;br /&gt;Java RMI is a powerful tool that leverages Java object serialization, allowing you to transparently work with objects on remote machines almost as if they were local. With RMI, it is easy to write distributed applications in which clients and servers work with each other's data as full-fledged Java objects rather than raw streams or packets of data. Technologies like Enterprise JavaBeans build on RMI and extend its semantics, so it is very important to understand the concepts involved.&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-bYe1EJTbBJw/Ta-3aDEFPmI/AAAAAAAAAAU/1y3aZlQg1Kk/s1600/figure1.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="320" src="http://2.bp.blogspot.com/-bYe1EJTbBJw/Ta-3aDEFPmI/AAAAAAAAAAU/1y3aZlQg1Kk/s320/figure1.png" width="234" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;When writing network applications, it's common to talk about clients and servers. The distinction is increasingly vague, but the side that initiates the conversation is usually considered the client. The side that accepts the request is usually the server. In the case where two peer applications use sockets to talk, the distinction is less important, but for simplicity we'll use this definition.&lt;br /&gt;&lt;br /&gt;For our purposes, the most important difference between a client and a server is that a client can create a socket to initiate a conversation with a server application at any time while a server must be prepared in advance to listen for incoming conversations. The java.net.Socket class represents one side of an individual socket connection on both the client and server. In addition, the server uses the java.net.ServerSocket class to listen for new connections from clients. In most cases, an application acting as a server creates a ServerSocket object and waits, blocked in a call to its accept( ) method, until a connection arrives. When it arrives, the accept( ) method creates a Socket object the server uses to communicate with the client. A server may carry on conversations with multiple clients at once; in this case, there is still only a single ServerSocket, but the server has multiple Socket objectsone associated with each client, as shown in Figure2.&lt;br /&gt;&lt;br /&gt;At the socket level, a client needs two pieces of information to locate and connect to a server on the Internet: a hostname (used to find the host's network address) and a port number. The port number is an identifier that differentiates between multiple clients or servers on the same host. A server application listens on a prearranged port while waiting for connections. Clients select the port number assigned to the service they want to access. If you think of the host computers as hotels and the applications as&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-eUsIArEFCO4/Ta-3lHzPEiI/AAAAAAAAAAY/-82a7K82XsI/s1600/figure2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="169" src="http://2.bp.blogspot.com/-eUsIArEFCO4/Ta-3lHzPEiI/AAAAAAAAAAY/-82a7K82XsI/s320/figure2.png" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;guests, the ports are like the guests' room numbers. For one person to call another, he or she must know the other party's hotel name and room number.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6709431659636147588-4842002603766192789?l=www.myg3nx.co.cc' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.myg3nx.co.cc/feeds/4842002603766192789/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.myg3nx.co.cc/2011/04/basic-knowledgetutorial-programming_20.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6709431659636147588/posts/default/4842002603766192789'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6709431659636147588/posts/default/4842002603766192789'/><link rel='alternate' type='text/html' href='http://www.myg3nx.co.cc/2011/04/basic-knowledgetutorial-programming_20.html' title='Basic Knowledge/Tutorial Programming About Socket in JAVA'/><author><name>haries</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://2.bp.blogspot.com/-bYe1EJTbBJw/Ta-3aDEFPmI/AAAAAAAAAAU/1y3aZlQg1Kk/s72-c/figure1.png' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6709431659636147588.post-6741247443450430560</id><published>2011-04-20T21:47:00.000-07:00</published><updated>2011-04-20T23:09:41.819-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='program'/><category scheme='http://www.blogger.com/atom/ns#' term='vb'/><category scheme='http://www.blogger.com/atom/ns#' term='socket'/><category scheme='http://www.blogger.com/atom/ns#' term='tutorial'/><category scheme='http://www.blogger.com/atom/ns#' term='c#'/><title type='text'>Basic Knowledge/Tutorial Programming About Socket in .NET</title><content type='html'>The Socket class provides a rich set of methods and properties for network communications. The Socket class allows you to perform both synchronous and asynchronous data transfer using any of the communication protocols listed in the ProtocolType enumeration. &lt;br /&gt;&lt;br /&gt;The Socket class follows the .NET Framework naming pattern for asynchronous methods. For example, the synchronous Receive method corresponds to the asynchronous BeginReceive and EndReceive methods.&lt;br /&gt;&lt;br /&gt;If your application only requires one thread during execution, use the following methods, which are designed for synchronous operation mode.&lt;br /&gt;&lt;br /&gt;&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;If you are using a connection-oriented protocol such as TCP, your server can listen for connections using the Listen method. The Accept method processes any incoming connection requests and returns a Socket that you can use to communicate data with the remote host. Use this returned Socket to call the Send or Receive method. Call the Bind method prior to calling the Listen method if you want to specify the local IP address and port number. Use a port number of zero if you want the underlying service provider to assign a free port for you. If you want to connect to a listening host, call the Connect method. To communicate data, call the Send or Receive method.&lt;br /&gt;&lt;br /&gt;If you are using a connectionless protocol such as UDP, you do not need to listen for connections at all. Call the ReceiveFrom method to accept any incoming datagrams. Use the SendTo method to send datagrams to a remote host.&lt;br /&gt;&lt;br /&gt;To process communications using separate threads during execution, use the following methods, which are designed for asynchronous operation mode.&lt;br /&gt;&lt;br /&gt;If you are using a connection-oriented protocol such as TCP, use the Socket, BeginConnect, and EndConnect methods to connect with a listening host. Use the BeginSend and EndSend or BeginReceive and EndReceive methods to communicate data asynchronously. Incoming connection requests can be processed using BeginAccept and EndAccept.&lt;br /&gt;&lt;br /&gt;If you are using a connectionless protocol such as UDP, you can use BeginSendTo and EndSendTo to send datagrams, and BeginReceiveFrom and EndReceiveFrom to receive datagrams.&lt;br /&gt;&lt;br /&gt;If you perform multiple asynchronous operations on a socket, they do not necessarily complete in the order in which they are started.&lt;br /&gt;&lt;br /&gt;When you are finished sending and receiving data, use the Shutdown method to disable the Socket. After calling Shutdown, call the Close method to release all resources associated with the Socket.&lt;br /&gt;&lt;br /&gt;The Socket class allows you to configure your Socket using the SetSocketOption method. Retrieve these settings using the GetSocketOption method.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6709431659636147588-6741247443450430560?l=www.myg3nx.co.cc' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.myg3nx.co.cc/feeds/6741247443450430560/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.myg3nx.co.cc/2011/04/basic-knowledgetutorial-programming.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6709431659636147588/posts/default/6741247443450430560'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6709431659636147588/posts/default/6741247443450430560'/><link rel='alternate' type='text/html' href='http://www.myg3nx.co.cc/2011/04/basic-knowledgetutorial-programming.html' title='Basic Knowledge/Tutorial Programming About Socket in .NET'/><author><name>haries</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry></feed>
