|
C# Socket Program Example
Create a new console application project. You can use the project and solution names as shown in the following Figure.
Add the following code. |
using System; using System.IO; using System.Net; using System.Text; using System.Net.Sockets;
namespace SocketChap6CS { /// <summary> /// This sample demonstrates the socket classes /// being used to download a Web page that is passed in on the command line. /// </summary> class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[ ] args) { // Validate the input values if (args.Length < 2) { Console.WriteLine("Usage: Executable_file_name serverName path"); Console.WriteLine("Example: Executable_file_name contoso.com /"); return; }
string server = args[0]; string path = args[1]; // Change accordingly... int port = 80;
IPHostEntry host = null; IPEndPoint remoteEndPoint = null; Socket client = null;
// Resolve the server name try { Console.WriteLine("Resolving the server name..."); host = Dns.GetHostEntry(server); } catch (Exception ex) { Console.WriteLine(ex.ToString()); return; }
// Attempt to connect on each address returned from DNS. Break out once successfully connected foreach (IPAddress address in host.AddressList) { try { client = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp); Console.WriteLine("Socket() is OK..."); remoteEndPoint = new IPEndPoint(address, port); client.Connect(remoteEndPoint); Console.WriteLine("Connect() is OK, address: " + address + ", port: " + port); break; } catch (SocketException ex) { Console.WriteLine(ex.ToString()); } }
// MakeRequest will issue the HTTP download request and write the server response to the console MakeRequest(client, path, server); Console.WriteLine("MakeRequest() is OK..."); client.Close(); Console.WriteLine("Closing client..."); }
public static void MakeRequest(Socket client, string path, string server) { // Format the HTTP GET request string string Get = "GET " + path + " HTTP/1.0\r\nHost: " + server + "\r\nConnection: Close\r\n\r\n"; Byte[] ByteGet = Encoding.ASCII.GetBytes(Get);
// Send the GET request to the connected server client.Send(ByteGet); Console.WriteLine("Send() is OK...");
// Create a buffer that is used to read the response byte[ ] responseData = new byte[1024];
// Read the response and save the ASCII data in a string int bytesRead = client.Receive(responseData); Console.WriteLine("Receive() is OK..."); StringBuilder responseString = new StringBuilder(); while (bytesRead != 0) { responseString.Append(Encoding.ASCII.GetChars(responseData), 0, bytesRead); bytesRead = client.Receive(responseData); } // Display the response to the console Console.WriteLine(responseString.ToString()); } } } |
Build and run the project (Start Without Debugging). The following are sample outputs when the executable was run at the command prompt.
Create a new console application project. You can use the project and solution name as shown in the following Figure.
Optionally you can change the Module name by changing the file name as shown in the following Figure.
|
![]() |
Add the following code.
Imports System Imports System.IO Imports System.Net Imports System.Text Imports System.Net.Sockets
' <summary> ' This sample demonstrates the socket classes ' being used to download a Web page that is passed in on the command line. ' </summary> Module SocketChap6VB
Sub Main(ByVal args As String()) ' Validate the input values If args.Length < 2 Then Console.WriteLine("Usage: Executable_file_name serverName path") Console.WriteLine("Example: Executable_file_name contoso.com /") Return End If
Dim server As String = args(0) Dim path As String = args(1) Dim port As Integer = 80 Dim host As IPHostEntry Dim remoteEndPoint As IPEndPoint Dim client As Socket = Nothing
' Resolve the server name Try host = Dns.GetHostEntry(server) Catch ex As Exception Console.WriteLine(ex.ToString()) Return End Try
' Attempt to connect on each address returned from DNS ' Break out once successfully connected For Each address As IPAddress In host.AddressList Try client = New Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp) Console.WriteLine("Socket() is OK...") remoteEndPoint = New IPEndPoint(address, port) client.Connect(remoteEndPoint) Console.WriteLine("Connect() is OK, IP address: {0}, port: {1}", address, port) Exit For Catch ex As Exception Console.WriteLine(ex.ToString()) End Try Next
' MakeRequest will issue the HTTP download request ' and write the server response to the console MakeRequest(client, path, server) Console.WriteLine("MakeRequest() is OK...") Console.WriteLine("Closing client...") client.Close() End Sub Sub MakeRequest(ByVal client As Socket, ByVal path As String, ByVal server As String)
' Format the HTTP GET request string Dim getString As String = "GET " + path + " HTTP/1.0" + ControlChars.CrLf getString += "Host: " + server + ControlChars.CrLf + "Connection: Close" getString += ControlChars.CrLf + ControlChars.CrLf
Dim ByteGet As Byte() = Encoding.ASCII.GetBytes(getString)
' Send the GET request to the connected server client.Send(ByteGet) Console.WriteLine("Send() is OK...")
' Create a buffer that is used to read the response Dim responseData() As Byte = New Byte(1024) {}
' Read the response and save the ASCII data in a string Dim bytesRead As Integer = client.Receive(responseData) Console.WriteLine("Receive() is OK...") Dim responseString As StringBuilder = New StringBuilder
While bytesRead > 0 responseString.Append(Encoding.ASCII.GetChars(responseData), 0, bytesRead) bytesRead = client.Receive(responseData) End While
' Display the response to the console Console.WriteLine(responseString.ToString()) End Sub End Module |
Build and run the project (Start Without Debugging). The following are sample outputs when the executable was run at the command prompt.