Working principle and code of socket communication

Keywords: Windows TCP/IP

Question:
1. What is the socket communication mechanism?
The official explanation is:
The most commonly used scheme in network programming is the client / server model. In this scenario, the client application requests services from the server program. A service program usually listens for requests for services at a well-known address, that is, the service process remains dormant until a customer makes a connection request to the address of the service. At this moment, the service program is "awakened" and provides services to customers - respond appropriately to customers' requests.

In order to facilitate the network programming of this Client/Server model, in the early 1990s, Microsoft and several other companies jointly formulated a set of network programming interface under windows, namely WindowsSockets specification. It is not a network protocol, but an open network programming interface under windows that supports multiple protocols. Now Winsock has basically realized that it is protocol independent. You can use Winsock to call the functions of various protocols, but TCP/IP protocol is often used. Socket actually provides a communication port in the computer, which can communicate with any computer with socket interface. Applications transmit and receive information on the network through this socket interface.

1. The premise of creating socket communication mechanism is:
Know the ip and port number of the server
Know the ip and port number of the client
Know the communication protocol

2. Working principle of socket:

3. Code implementation phase:
Main ideas:
1. Establish socket
2. Bind native ip and port number
3. tcp protocol to monitor whether a send request is received
4. Close connection

//Server side code
int recv;   //Length of data sent by receiving client
byte[] data=new byte[1024];     //y is used to cache the data information sent by the client. The information sent by the client must be sent in the form of array
//Reserve the ip and port number of the machine and create a listening point
IPEndPoint ipep=new IPEndPoint(IPAddress.Any(ip address),8080(port Port number));
//New socket, c create channel
socket mysocket=new socket(AddressFamily.internetwork,sockettype.stream,potocoltype.tcp;)
//Bind socket, bind ip and port number of client

mysocket.bind(ipep);
//monitor
mysocket.listen(10);
 Executes when a client connection attempt is available and returns a new one socket,Used for communication with clients 
socket nextsocket=mysocket.Accept();
//Cast the client ip address of the next connection to the ipendpoint type
IPEndPoint clientip=(IPEndPoint)nextclient.RemoteEndPoint;
string send_txt="hello world";
//Parse the received data
data=Encoding.AscII.GetBytes(send_txt);
//send data
nextclient.send(data.data.length,socketFlags.none);
//Get data from client
while(true)
{
	data=new byte[1024];
	recv=nextclient.receive(data);
	console.writeline("recv="+recv);
	if(recv==0)
	{
		//The received data length is 0, indicating that the connection is disconnected
		break;
	}
	//Analyze the received data information and output it to the console
	console.writeline(Encoding.ASCLL.GstString(data,0,recv));
	nextclient.send(data,recv,socketflags.none);
}

nextclient.close();
mysocket.close();
}
}
//Client code
//Reserved receive data cache array
byte[] data=new byte[1024];
//Create socket, create channel
socket newclient=new socket(AddressFamily.Interwork,SocketType.stream,ProtocolType.none);
console.writeline("Please enter the server ip address");
//Create listening point, ip, port number
string ipaddress=console.readline();
console.writeline("Please enter the server port number");
int port=convet.ToInt32(console.readline());
IPEndPoint ipep=new IPEndPoint(AddressFamily.InterNetWork,SocketType.stream,ProtocolType.none);
//connect
try
{
	//Because the client sends a request to a specific server, there is no need to bind the local ip and port number,
And no monitoring is required
	//connect
	newclient.connect(ipep);
}
catch(Exception ex)
{
	alert("Connection failed, failure reason:"+ex.tostring());
	return;
}
int recv=newclient.receive(data);
string stringdata=Encoding.ASCII.GetString(data0,recv);     ??
cosole.writeline(stringdata);
//Send a request to the server in a loop
while(true)
{
	string input=console.readline();
	if(input=="exit")
		break;
	newclient.send(Encoding.ASCLL.GetBytes(input));	
	data=new byte[1024];
	recv=newclient.receive(data);
	stringdata=Encoding.ASCLL.GetString(data,0,recv);    
	console.writeline(stringdata);

}
newclient.ShutDown(socketShutdown.both);
newclient.close();


If you have any questions, please give me more advice!!

Posted by andynick on Mon, 20 Sep 2021 05:41:02 -0700