Python3 (Socket implementation UDP,TCP socket programming)

Source: Internet
Author: User

#coding =utf-8# client program TCP connection import Sockets=socket.socket (Socket.af_inet,socket. Sock_stream) S.connect ((' 127.0.0.1 ', 9999)) print (S.RECV (1024x768)) for data in [' Michael ', ' Tracy ', ' Sarah ']:    s.send ( Data.encode ())    print (S.RECV (1024x768)) S.send (b ' exit ')
#coding =utf-8#tcp Server-side program import Socketimport timeimport threadingdef tcplink (sock,addr):    print ("Accept new Connection from%s:%s ... "% addr)    sock.send (" welcom! ". Encode ()) while    True:        data=sock.recv (1024x768)        time.sleep (1)        if data== ' exit ' or not data:            break        sock.send ("Hello:". Encode () +data)    sock.close ()    print ("Connection from%s:%s closed."% addr)        s= Socket.socket (Socket.af_inet,socket. SOCK_STREAM)  # Create a Sockets.bind ((' 127.0.0.1 ', 9999)) of the TCP protocol based on IPv4  #监听端口s. Listen (5) print ("Waiting for Connection ... ") while True:    sock,addr=s.accept ()    t=threading. Thread (target=tcplink,args= (sock, addr))    T.start ()    

Operation Result:

Waiting for connection......accept new connection from 127.0.0.1:60218...connection to 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 Code import sockets=socket.socket (Socket.af_inet,socket. SOCK_DGRAM) for data in ["Chenshan", "Yuanhui", "Chendianqiang"]:    s.sendto (Data.encode (), (' 127.0.0.1 ', 9999))    Print (S.RECV (1024x768))    S.close ()
#coding =UTF-8#UDP Protocol Server Code import sockets=socket.socket (Socket.af_inet,socket. SOCK_DGRAM) S.bind ((' 127.0.0.1 ', 9999)) print ("Bind UDP on prot:9999") while True:    data,addr=s.recvfrom (1024x768)    Print ("Receive from%s:%s"% addr)    s.sendto ("Hello". Encode () +data,addr)

Python3 (Socket implementation UDP,TCP socket programming)

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.