socket concept socket

 

understand socket

Socket is a middleware abstraction layer that communicates between the application layer and the TCP/IP protocol suite. It is a set of interfaces. In the design mode, Socket is actually a facade mode, which hides the complex TCP/IP protocol family behind the Socket interface. For users, a set of simple interfaces is all, and let the Socket organize the data to meet the specified requirements. protocol.


In fact, from your point of view, a socket is a module. We establish the connection and communication between the two processes by calling the methods already implemented in the module. Some people also say socket as ip+port, because ip is used to identify the location of a host in the Internet, and port is used to identify an application on this machine. So we can find an application as long as we establish the ip and port, and use the socket module to communicate with it.

socket layer

 

Initial use of sockets

socket based on TCP protocol

tcp is based on the link, you must start the server first, and then start the client to link the server

 

server side

import socket
sk = socket.socket()
sk.bind(( ' 127.0.0.1 ' ,8898))   #Bind the address to the socket. This ip address and port are the address and port you want to connect to 
sk.listen() #Listen           to the link 
conn,addr = sk.accept() #Accept client link 
ret = conn.recv(1024) #Receive   client information 
print (ret)        #Print client information 
conn.send(b ' hi ' )         # Send information to client 
conn.close ()        #Close the client socket 
sk.close() #Close         the server socket (optional)

client side

import socket
sk = socket.socket() #Create            a client socket 
sk.connect(( ' 127.0.0.1 ' ,8898))     #try to connect to the server 
sk.send(b'hello ! ' )
ret = sk.recv(1024) #Dialog (          send /receive) 
print (ret)
sk.close() #Close             the client socket

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325256466&siteId=291194637