Python Learning 5 Network programming-TCP/UDP

Source: Internet
Author: User

Excerpt from: Liaoche's official website: http://www.liaoxuefeng.com/

TCP client and server-side code:

#Coding=utf-8#client program TCP connectionImportSockets=Socket.socket (Socket.af_inet,socket. Sock_stream) S.connect (('127.0.0.1', 9999))Print(S.RECV (1024)) forDatainch['Michael','Tracy','Sarah']: S.send (Data.encode ())Print(S.RECV (1024)) S.send (b'Exit')
#Coding=utf-8#TCP server-side programsImportSocketImport TimeImportThreadingdefTcplink (sock,addr):Print("Accept new connection from%s:%s ..."%addr) Sock.send ("welcom!". Encode ()) whileTrue:data=SOCK.RECV (1024) Time.sleep (1)        ifdata=='Exit' or  notData: BreakSock.send ("Hello:". Encode () +data) Sock.close ()Print("Connection from%s:%s closed."%addr) S=socket.socket (Socket.af_inet,socket. SOCK_STREAM)#create a socket based on the IPv4 TCP protocolS.bind (('127.0.0.1', 9999))#Listening PortS.listen (5)Print("waiting for connection ...") whiletrue:sock,addr=s.accept () T=threading. Thread (target=tcplink,args=(sock, addr)) T.start ()

Operation Result:

for from 127.0.0.1:60218 from 127.0.0.1:60218 closed. 
b'welcom! ' b ' Hello:michael ' b ' hello:tracy ' b ' Hello:sarah '

UDP client and server-side code:

#Coding=utf-8#UDP Client CodeImportSockets=Socket.socket (Socket.af_inet,socket. SOCK_DGRAM) forDatainch["Chenshan","Yuanhui","Chendianqiang"]: S.sendto (Data.encode (), ('127.0.0.1', 9999))    Print(S.RECV (1024) ) S.close ()
#Coding=utf-8#UDP Protocol Server CodeImportSockets=Socket.socket (Socket.af_inet,socket. SOCK_DGRAM) S.bind (('127.0.0.1', 9999))Print("Bind UDP on prot:9999") whiletrue:data,addr=s.recvfrom (1024)    Print("Receive from%s:%s"%addr) s.sendto ("Hello". Encode () +data,addr)

Operation Result:

Bind UDP on prot:9999
b'hello chenshan'b'hello yuanhui'b ' Hello Chendianqiang '

Python Learning 5 Network programming-TCP/UDP

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.