Socket-based communication protocol tcp

To call, for example:

Import Socket 

# 1. Buy Mobile 
Phone = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
 # SOCK_STEAM => the TCP protocol flow, 

# 2. Dial 
phone.connect (( ' 127.0.0.1 ' , 8080 )) 

# . 3 . send \ receive message 
phone.send ( ' Hello ' .encode ( ' UTF-. 8 ' )) # can only send bytes type 
Data = phone.recv (1024 )
 Print ( ' receive the message server: ' , Data) 

# 4. hang link 
phone.close ()
Client
Import Socket 

# 1. Buy Mobile 
Phone = socket.socket (socket.AF_INET, socket.SOCK_STREAM) # SOCK_STEAM => the TCP protocol flow, 
Print (Phone) # is used to receive a link request to establish a link 
# Results: < FD = 268 socket.socket, Family AddressFamily.AF_INET =, = SocketKind.SOCK_STREAM type, proto = 0> 
# 2. phone card inserted 
phone.bind (( ' 127.0.0.1 ' , 8080)) # 0-65535 

# . 3. power 
phone.listen (. 5) # same time the maximum number of requests to 5 

Print ( ' Start .... ' )
 # 4. wait for calling request 
Conn, client_addr phone.accept = () #(Socket object bidirectional links, and storing the client ip small port tuple) 
Print (Conn) # Conn representative of bidirectional link, to send and receive messages 
# Results: <socket.socket fd = 304, family = AddressFamily.AF_INET , type = SocketKind.SOCK_STREAM, proto = 0, LADDR = ( '127.0.0.1', 8080), RADDR = ( '127.0.0.1', 3482)> 
Print (client_addr)
 # results :( '127.0.0.1', 3482 ) 

# 5 received \ message 
data = conn.recv (1024) # 1024 the maximum number of bytes received bytes 
Print ( ' received customer data ' , data) 
conn.send (data.upper ()) 

# . 6. hang link 
conn.Close () 

# 7. shutdown 
phone.close ()
Server

 

Guess you like

Origin www.cnblogs.com/zhouhao123/p/11267594.html