python-tcp server to service multiple clients

socket Import 


DEF main ():
# 1. Create a socket
tcp_server_socket = socket.socket (socket.AF_INET, socket.SOCK_STREAM)

# 2. Bind local information
tcp_server_socket.bind (( '', 1234))

# 3. Let the default socket becomes passive the listen
tcp_server_socket.listen (128)

the while True: # multiple client service
# 4. wait for customers link the Accept
new_client_socket, client_addr = tcp_server_socket.accept ()

the while True: # for this client and more secondary service
# 5 segments sent, the customer accepts the request
recv_data = new_client_socket.recv (1024)
Print (recv_data, recv_data.decode ( 'GBK')) # bytes is passed back in front of the type, for decoding the back

IF recv_data:
#. 6 a portion of the data sent back to the client
new_client_socket.send ( 'It \' S ok'.encode ( 'UTF-. 8'))
the else:
Print ( 'has been completed for the client service')
BREAK

# 7. The socket is closed
new_client_socket.close ()
tcp_server_socket. Close ()

IF the __name__ == '__main__':
main ()

Guess you like

Origin www.cnblogs.com/fuyouqiang/p/11767317.html