clients, client code:
Client Main method, S.send (); S.sendall (); S.recv (); S.connect ()
Class Client (object):
def __init__ (self, IP, portno=xxx):
Self.ip = IP
Self. PortNo = PortNo
def connect_socket (self):
Count = 1
Status = 0
While count < 6 and Status = = 0: # try 5 times in Ip::port No on the Create socket link.
Print ("Attempt%s time (s) to open socket port"% count)
Try
Self.soct = Socket.socket (socket.af_inet, socket. SOCK_STREAM) # define socket type (TCP)
Except Socket.error, E: # Socket error exception handling, here put Exception catch, the code can continue to run. The end of the function returns a function run result flag for the main function or call function to judge.
Print ("error occur during creating socket::%s"% e)
Try
Self.soct.connect (Self.ip, self. PORTNO))
Status = 1
Print ("Socket opened success:%s::%s"% (Self.ip, self.) PORTNO))
Except Socket.error, E: # Common Socket error has destination address Errors, PortNo, firewalls and other reasons
Print ("Address or port related error detected during connect to server::%s"% e)
Count + = 1
Time.sleep (3)
If status = = 0:
Return False
Return True # returns function Run result
Server, service-side code,
Service-side Main method, S.recv (); S.send (); S.sendall (); S.bind (); S.close ()
Class Server (object):
def __init__ (self, IP, portno=xxx):
Self.ip = IP
Self. PortNo = PortNo
def run_server (self):
Self.soct = Socket.socket (socket.af_inet, socket. SOCK_STREAM) # define socket type (TCP)
Self.scot.bind (self.ip,self. PORTNO))
Self.soct.listen (1) # Number of socket listeners.
CONN,ADDR = Self.soct.accept () # accepts Scoket link request.
Print ("Socket has been established with%s::%s"% (CONN,ADDR))
While True:
Data_r = SELF.SOCT.RECV (1024) # Accept data from socket
Print ("Received%s from socket"% data_r)
Self.soct.sendall ("data_s") # Send data to the socket
Print ("Send data%s to socket"% data_s)
Self.soct.close () # End the created socket Method.
Python socket (single thread)