A detailed explanation of the handshake between the client and the server of python Socket, pythonsocket
In simple learning, socket is used to establish a connection between the client and the server and send data.
1. Client socketClient. py code
Import socket s = socket. socket (socket. AF_INET, socket. SOCK_STREAM) # establish a connection: s. connect ('2017. 0.0.1 ', 9999) # receive the welcome message: print (s. recv (1, 1024 ). decode ('utf-8') for data in [B 'Michael', B 'Tracy', B 'Sarah']: # send data: s. send (data) print (s. recv (1, 1024 ). decode ('utf-8') s. send (B 'exit ') s. close ()
2. Server 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 ('2017. 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 (1024) time. sleep (1) if not data or data. decode ('utf-8') = 'eg': break sock. send ('hello, % s! '% Data. decode ('utf-8 ')). encode ('utf-8') sock. close () print ('Connection from % s: % s closed. '% addr) while True: # accept a new connection: sock, addr = s. accept () # create a new thread to process TCP connections: t = threading. thread (target = tcplink, args = (sock, addr) t. start ()
3. Operation Process
Open two console windows and run python3 serverSocket. py on the server first.
Then run the client python3 socketClient. py
The socket connection is as follows:
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.