Python Socket Programming

Source: Internet
Author: User

Soket Programming Steps

#-*-coding:utf-8-*-########################################################################classSckt:"""go to vowel abbreviation variable name"""    #----------------------------------------------------------------------    def __init__(Self, host ='127.0.0.1', Port = 10000):        """Address Initialization"""Self.host=host Self.port=Port#----------------------------------------------------------------------    defRun_server (self):"""Server"""        ImportSocket"""The first step is to create the socket object"""Sckt=Socket.socket (socket.af_inet, socket. SOCK_STREAM)"""The second step is to bind the socket to the specified address"""Sckt.bind ((Self.host, self.port))"""The third step is to receive the connection request using the Listen method of the socket socket"""Sckt.listen (5)         whileTrue:"""The fourth step is that the server socket waits for the client to request a connection via the socket's Accept method"""Connection, Address=sckt.accept ()Try:                """The fifth step is the processing phase, where the server and client communicate via the Send and Recv methods"""Connection.settimeout (5) Buffer= CONNECTION.RECV (1024)                ifBuffer = ='1': Connection.send ('Welcome to server!')                Else: Connection.send ('Cut off the connection!')            exceptsocket.timeout:Print('Time out!')            """finally the transfer ends, the server calls the socket's Close method to close the connection"""connection.close ()#----------------------------------------------------------------------    defrun_client (self):"""Client"""        ImportSocket"""The first step is to create the socket object"""Sckt=Socket.socket (socket.af_inet, socket. SOCK_STREAM)"""The second step is to connect the server"""Sckt.connect ((Self.host, self.port))ImportTime Time.sleep (2)        """The third step is communication"""Sckt.send ('1')        Print(SCKT.RECV (1024))        """Finally, close the connection ."""sckt.close ()

Python 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: [email protected] 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.