Share via


Using a Synchronous Client Socket

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.

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.

Dim msg As Byte() = _
    System.Text.Encoding.ASCII.GetBytes("This is a test.")
Dim bytesSent As Integer = s.Send(msg)
byte[] msg = System.Text.Encoding.ASCII.GetBytes("This is a test");
int bytesSent = s.Send(msg);

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.

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.

Dim bytes(1024) As Byte
Dim bytesRec = s.Receive(bytes)
Console.WriteLine("Echoed text = {0}", _
    System.Text.Encoding.ASCII.GetString(bytes, 0, bytesRec))
byte[] bytes = new byte[1024];
int bytesRec = s.Receive(bytes);
Console.WriteLine("Echoed text = {0}",
    System.Text.Encoding.ASCII.GetString(bytes, 0, bytesRec));

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.

s.Shutdown(SocketShutdown.Both)
s.Close()
s.Shutdown(SocketShutdown.Both);
s.Close();

See Also

Concepts

Using an Asynchronous Client Socket

Listening with Sockets

Synchronous Client Socket Example