TCP Programming--Server
1 Importsocket, threading, time2 3 defdealclient (sock, addr):4 Print('Accept New connection from%s:%s ...'%addr)5Sock.send (b'Hello, I am server!')#send data to client side6 whileTrue:7data = SOCK.RECV (1024)#receive data sent by the client8Time.sleep (1)9 if notDataorData.decode ('Utf-8') =='Exit':Ten Break One Print('-->>%s!'% Data.decode ('Utf-8')) ASock.send (('loop_msg:%s!'% Data.decode ('Utf-8')). Encode ())#send data to client - sock.close () - Print('Connection from%s:%s closed'%addr) the - if __name__=='__main__': - #create socket and bind IP -s =Socket.socket () +S.bind (('127.0.0.1', 9999)) -S.listen ()#Enable monitoring + Print('waiting for connection ...') A whileTrue: atSock, addr = S.accept ()#receive a new connection -t = Threading. Thread (target = dealclient, args = (sock, addr))#Create a new thread to handle a TCP connection -T.start ()
TCP Programming--Client
1 ImportSocket2 3s =Socket.socket ()4S.connect (('127.0.0.1', 9999))#Establish a connection5 Print('-->>'+ S.RECV (1024x768). Decode ('Utf-8'))#Receiving Messages6S.send (b'Hello, I am a client')7 Print('-->>'+ S.RECV (1024x768). Decode ('Utf-8'))8S.send (b'Exit')#Send Message9S.close ()
Code excerpt from Python Crawler development and project--mechanical industry press
Learning notes-Python network programming