The Socket class provides a wide range of methods and properties for network communications. The Socket class allows you to perform asynchronous and synchronous data transfer any of the protocols listed in the ProtocolType enumeration. The Socket class follows the .NET Framework naming mode of the asynchronous method; for example, the synchronous Receive method corresponds to the asynchronous BEGINRECEIVE and EndReceive methods. If the application only needs one thread during execution, use the following method, these methods apply to synchronous mode of operation. If the currently used protocol (such as TCP), the server can listen to the connection using the Listen method. The Accept method handles any incoming connection request and returns a socket that can be used to communicate with the remote host. You can use this returned Socket to call the Send or Receive method. If you want to specify a local IP address and port number, call the BIND method before calling the Listen method. If Bind is not called, the underlying service provider will assign these values for you. Thereafter, you can use the LocalendPoint property to identify the IP address and port number assigned to the socket. If you want to connect to a listener host, call the Connect method. To perform data communication, call the Send or Receive method. If the currently useless connection protocol (such as UDP), you do not need to listen. Call the ReceiveFrom method Accept any incoming datagram. Use the Sendto method to send the datagram to the remote host. To use a separate thread to process communication during the execution, use the following method, these methods apply to asynchronous mode of operation. If the currently used protocol (such as TCP), Socket, BegInConnect, and EndConnect methods can be used to connect to the listening host. Asynchronous data communication can be performed by using the BegInsend and Endsend methods or using the BeginReceive and EndRecEive methods. You can use BeginAccept and Endaccept to process incoming connection requests. If the currently useless connection protocol (such as UDP), BegInsendto and EndsendTo can be used to send datagrams, and use BeginReceiveFrom and endReceiveFrom to receive datagrams. After the data transmission and data reception are completed, use the shutdown method to disable the socket. After calling ShutDown, a Close method can be called to release all resources associated with socket. The Socket class allows the Socket to be configured using the SetSocketOption method. These settings can be retrieved using the GetSocketoption method. Note If you write a simpler application, and you can consider using TCPClient, TCPListener, and UDPClient by simultaneous data transmission. These classes provide simple and more friendly interfaces for Socket communication. Example [Visual C #] The following example shows how to use the socket class to send data and receive responses to the HTTP server.
Using system.text; using system.net; using system.net.sockets;
public class mySocket {private static Socket connectSocket (string server, int port) {Socket s = null; IPHostEntry iphe = null; try {// Get host related information iphe = Dns.Resolve (server);. // Loop through the AddressList to obtain the supported AddressFamily. This is to avoid // an exception to be thrown if the host IP address is not compatible with the address family // (typical in the IPv6 case). foreach (IPAddress ipad in iphe.AddressList) {IPEndPoint IPE = New IpendPoint (iPad, Port); Socket TMPS = New Socket (Ipe.AddressFamily, SocketType.Stream, Protocoltype.tcp);
TMPS.CONNECT (IPE);
IF (tmps.connected) {s = tmps; break;} else continue;}} catch (socketexce) {Console.Writeline ("Socketexception Caught !!!); console.writeline (" Source: " E.Source Console.writeline ("MESSAGE:" E.MESSAGE);} catches ("Exception E) {Console.writeline (" Exception Caught !!! "); console.writeline (" Source: " E.Source); Console.writeline ("Message:" E.MESSAGE);
}
// This method requests the home page content for the passed server. // It displays the number of bytes received and the page content. Private static string socketSendReceive (string server, int port) {// Set up variables and String to write to The server. Encoding ascii = encoding.ascii; string get = "Get / http / 1.1 / r / nhost:" Server "/ r / nConnection: close / r / n / r / n"; byte [] byteget = Ascii.getbytes (get); Byte [] recvbytes = new byte [256]; string strretpage = null; // create a socket connection with the specified server and port. Socket s = connectsocket (Server, port);
IF (s == null) Return ("Connection Failed"); // Send Request to the Server. S.send (Byteget, Byteget.Length, 0); // Receive The Server Home Page Content. Int32 Bytes = s. RecEive (RecvBytes, Recvbytes.length, 0);
// read the first 256 bytes. Strretpage = "default html page on" Server ": / r / n"; strretpage = strretpage ascii.getstring (recvbytes, 0, bytes);
while (bytes> 0) {bytes = s.Receive (RecvBytes, RecvBytes.Length, 0); strRetPage = strRetPage ASCII.GetString (RecvBytes, 0, bytes);} return strRetPage;} public static void Main (string [] Args) {String Host; int port = 80;
IF (args.length == 0) // if no server name is passed as argument to this program, use the current// Host name as default. Host = DNS.GETHOSTNAME (); else host = args [0];