Synchronizing client Sockets sample
The following example program creates a client that is connected to the server. The client is generated with a synchronous socket, so the 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 in the console.
C#
using System;
using System.Net;
using System.Net.Sockets; The
using System. Text;
public class Synchronoussocketclient {
public static void Startclient () {
//Data buffer for incoming data. byte[] bytes = new byte[1024];
//Connect to a remote device.
try {
//establish the remote endpoint for the socket.
//This example uses port 11000 on the local computer.
Iphostentry iphostinfo = Dns.resolve (Dns.gethostname ())
IPAddress ipaddress = iphostinfo.addresslist[0];
IPEndPoint remoteep = new IPEndPoint (ipaddress,11000);
//Create a TCP/IP socket.
Socket sender = new socket (addressfamily.internetwork,
SocketType.Stream, protocoltype.tcp);
//Connect the Socket to the remote endpoint. Catch any errors.
try {
Sender. Connect (remoteEP);
Console.WriteLine ("Socket connected to {0}",
Sender. Remoteendpoint.tostring ()); The
//Encode The data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes("This is a test<eof>");
//Send the data through the socket.
int bytessent = sender. Send (msg);
//Receive The response from the remote device.
int bytesrec = sender. Receive (bytes);
Console.WriteLine ("echoed Test = {0}",
Encoding.ASCII.GetString (Bytes,0,bytesrec));
//release the socket.
Sender. Shutdown (Socketshutdown.both);
Sender. Close ();
} catch (ArgumentNullException ane) {
Console.WriteLine ("ArgumentNullException: {0}", ane. ToString ());
} catch (SocketException se) {
Console.WriteLine ("SocketException: {0}", se. ToString ());
} catch (Exception e) {
Console.WriteLine ("Unexpected Exception: {0}", e.tostring ());
}
} catch (Exception e) {
Console.WriteLine (e.tostring ());
}
}
public static int Main (string[] args) {
startclient ();
return 0;
}
}