SoFunction
Updated on 2025-04-13

Visual C#.Net Network Program Development - Socket


After determining the address of the remote device and selecting the port for connection, the application can try to establish a connection to the remote device. The following example uses an existing IPEndPoint instance to connect to a remote device and catch possible exceptions:

try { 
(ipe);//Try to connect

//The processing parameter is empty reference exception
catch(ArgumentNullException ae) { 
("ArgumentNullException : {0}", ()); 

//handle operating system exceptions
catch(SocketException se) { 
("SocketException : {0}", ()); 

catch(Exception e) { 
("Unexpected exception : {0}", ()); 



What you need to know is that the Socket class supports two basic modes: synchronization and asynchronous. The difference is that in synchronization mode, the call to functions that perform network operations (such as Send and Receive) will not return control to the calling program until the operation is completed. In asynchronous mode, these calls are returned immediately.

In addition, many times, Socket programming needs to be implemented separately on the client and the server side depending on the situation. The client compiles the application to send a request to the server designated port, and the server application to process the request. This process has been mentioned in the above explanation; of course, not all Socket programming requires you to strictly write these two programs; depending on the application situation, you can construct a request string on the client, and the corresponding port of the server captures the request and hand it over to its public service program for processing. The string in the following example statement makes a page request to the remote host:

string Get = "GET / HTTP/1.1\r\nHost: " + server + "\r\nConnection: Close\r\n\r\n"; 


After the remote host's designated port accepts this request, it can use its public service program to process it without the need to compile a server-side application separately.

Comprehensively use the knowledge of using Visual C# for Socket network program development as explained above, the following program segment fully realizes the web page download function. Users can obtain the remote host page and save it in the local file name on the form (Dns host name or IP address in the four-part notation format separated by dots) and the pre-save local file name, and use port 80 that specifically provides Http service to obtain the remote host page and save it in the local machine specified file. If the save format is in .htm format, you can open the page in your Internet browser. Adding the code appropriately, you can even implement a simple browser program.


The main source code for implementing this function is as follows:

//"Start" button event
private void button1_Click(object sender,  e) { 
//Get the pre-save file name
string fileName=(); 
//Remote host
string hostName=(); 
//Port
int port=(()); 
//Get host information
IPHostEntry ipInfo=(hostName); 
//Get IPAddress[]
IPAddress[] ipAddr=; 
//Get ip
IPAddress ip=ipAddr[0]; 
//Combining remote endpoint
IPEndPoint hostEP=new IPEndPoint(ip,port); 
//Create a Socket instance
Socket socket=new Socket(,,); 
try 

//Try to connect
(hostEP); 

catch(Exception se) 

("Connection Error"+," prompt message
,,); 

//The request content string sent to the remote host
string sendStr="GET / HTTP/1.1\r\nHost: " + hostName + 
"\r\nConnection: Close\r\n\r\n"; 
//Create a byte array to convert the send string
byte[] bytesSendStr=new byte[1024]; 
//Convert the sent content string into a byte byte array
bytesSendStr=(sendStr); 
try 

//Send a request to the host
(bytesSendStr,,0); 

catch(Exception ce) 

("Send error:"+," prompt message
,,); 

//Declare the string that receives the returned content
string recvStr=""; 
//Declare the byte array, the length of the data received at one time is 1024 bytes.
byte[] recvBytes=new byte[1024]; 
//Return the number of bytes of the actual received content
int bytes=0; 
//Read it loops until all data is received
while(true) 

bytes=(recvBytes,,0); 
//Exit the loop after reading is completed
if(bytes<=0) 
break; 
//Convert the number of read bytes into a string
recvStr+=(recvBytes,0,bytes); 

//Convert the read string into a byte array
byte[] content=(recvStr); 
try 

//Create a file stream object instance
FileStream fs=new FileStream(fileName,,); 
//Write to file
(content,0,); 

catch(Exception fe) 

("File creation/write error:"+,"Prompt message",,);

//Disable Socket
(); 
//Close Socket
(); 




The program is debugged and passed in the Windows XP Chinese version, .Net Frameworkd Chinese official version, and Visual Chinese official version.


About the author

Song Hua graduated from the Department of Electronics and Electrical, Chengde Petroleum College in 1996 and joined the Tuha Oilfield in Tuha Oilfield in China National Petroleum Corporation in the same year. He has been engaged in network planning and construction, website architecture and design, and is currently specializing in Internet application development and Windows application development.