The socket of the Python module

Source: Internet
Author: User

43, the Python module socket:

Python is powerful in network communication, learn the basic way of socket communication

UDP communication:

Server:

Import Socketport=8081s=socket.socket (Socket.af_inet,socket. SOCK_DGRAM) #从指定的端口, from any sender, receives the UDP data S.bind ((", port)) print (' Waiting for access ... ') while True:    #接收一个数据    data,addr= S.recvfrom    Print (' Received: ', data, ' from ', addr)

Client:

Import socketport=8081host= ' localhost ' s=socket.socket (socket.af_inet,socket. SOCK_DGRAM) s.sendto (b ' Hello,this is a test info! ', (Host,port))


Very simple. Here is the TCP method:

Server:

#-*-coding:utf-8-*-from Socket import *from time import ctimehost= ' port=12345bufsiz=1024addr= (HOST, PORT) sock=socket (Af_inet, Sock_stream) sock.bind (ADDR) Sock.listen (5) while True:    print (' Waiting for connection ')    Tcpclientsock, addr=sock.accept ()    print (' Connect from ', addr) while    True:        try:            data= TCPCLIENTSOCK.RECV (Bufsiz)        except:            print (e)            tcpclientsock.close ()            break        if not data:            Break        s= ' hi,you send me: [%s]%s '% (CTime (), Data.decode (' UTF8 '))        tcpclientsock.send (S.encode (' UTF8 '))        print ([CTime ()], ': ', Data.decode (' UTF8 ')) tcpclientsock.close () Sock.close ()

Client:

#-*-coding:utf-8-*-from Socket import *class TcpClient:    host= ' 127.0.0.1 '    port=12345    bufsiz=1024    Addr= (HOST, PORT)    def __init__ (self):        self.client=socket (Af_inet, Sock_stream)        Self.client.connect ( Self. ADDR) while        True:            data=input (' > ')            if not data:                break            self.client.send (Data.encode (' UTF8 ' ))            data=self.client.recv (self. BUFSIZ)            If not data:                break            print (Data.decode (' UTF8 '))            if __name__ = = ' __main__ ':    client= TcpClient ()

There is a problem with TCP above, we can not quit, OK, let's change it so that the program could send the QUIT command to exit:

Server:

#-*-coding:utf-8-*-from Socket import *from time import ctimefrom time import localtimeimport timehost= ' port=1122 #设置 Listening Port bufsiz=1024addr= (HOST, Port) sock=socket (Af_inet, Sock_stream) sock.bind (ADDR) Sock.listen (5) #设置退出条件STOP_CHAT = Falsewhile not Stop_chat:print (' Waiting for access, listening port:%d ' (port)) Tcpclientsock, addr=sock.accept () print (' Accept connection, client address: ', ad DR) while True:try:data=tcpclientsock.recv (Bufsiz) except: #print (E) t Cpclientsock.close () Break if not data:break #python3使用bytes, so encode #s = '%s sent to My message is: [%s]%s '% (Addr[0],ctime (), Data.decode (' UTF8 ')) #对日期进行一下格式化 isotimeformat= '%y-%m-%d%x ' stime= Time.strftime (Isotimeformat, LocalTime ()) s= '%s sent me the message is:%s '% (Addr[0],data.decode (' UTF8 ')) Tcpclientsock.sen D (S.encode (' UTF8 ')) print ([Stime], ': ', Data.decode (' UTF8 ')) #如果输入quit (ignoring case), the program exits stop_chat= (DATA.D     Ecode (' UTF8 '). Upper () = = "QUIT")   If STOP_CHAT:breaktcpClientSock.close () Sock.close () 

Client:

#-*-coding:utf-8-*-from Socket import *class TcpClient:    #测试, connect the native    host= ' 127.0.0.1 '    #设置侦听端口    port= 1122     bufsiz=1024    addr= (HOST, PORT)    def __init__ (self):        self.client=socket (Af_inet, Sock_stream)        Self.client.connect (self. ADDR)        while True:            data=input (' > ')            if not data:                break            #python3传递的是bytes, so encode            Self.client.send (Data.encode (' UTF8 '))            print (' Send message to%s:%s '% (self). Host,data))            if data.upper () = = "QUIT": Break                        data=self.client.recv (self. BUFSIZ)            If not data:                break            print (' info received from%s:%s '% (self). Host,data.decode (' UTF8 ')))                        if __name__ = = ' __main__ ':    client=tcpclient ()

Note: The above code is PYTHON3.

The socket of the Python module

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.