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