This article mainly for you in detail the Python socket client and service side handshake, with a certain reference value, interested in small partners can refer to
Simple learning to use the socket to establish a connection between the client and the server and send the data
1. Client socketclient.py Code
Import socket s = socket.socket (socket.af_inet, socket. SOCK_STREAM) # Establish connection: S.connect ((' 127.0.0.1 ', 9999)) # Receive Welcome message: print (S.RECV (1024x768). Decode (' Utf-8 ')) for data in [B ' Michael ' , B ' Tracy ', B ' Sarah ': # Send data: s.send (data) print (S.RECV (1024x768). Decode (' Utf-8 ')) S.send (b ' exit ') s.close ()
2. Service-side serversocket.py code
Import Socket Import threading import time # from threading import Thread s = socket.socket (socket.af_inet, socket. SOCK_STREAM) # Listening Port: S.bind ((' 127.0.0.1 ', 9999)) S.listen (5) print (' Waiting for connection ... ') def tcplink (SOCK, Addr): print (' Accept new connection from%s:%s ... '% addr) sock.send (b ' welcome! ') While True: data = SOCK.RECV (1024x768) time.sleep (1) if not data or Data.decode (' utf-8 ') = = ' exit ': break< C9/>sock.send (' Hello,%s! '% data.decode (' Utf-8 ')). Encode (' Utf-8 ')) sock.close () print (' Connection from %s:%s closed. '% addr) while True: # accepts a new connection: sock, addr = S.accept () # Create a new thread to handle the TCP connection: t = Threa Ding. Thread (Target=tcplink, args= (sock, addr)) T.start ()
3. Operation Process
Open two console windows, run server Python3 serversocket.py first
Then run the client Python3 socketclient.py
The socket connection is as follows