1 #!/usr/bin/python2 #Coding=utf-83 #Server4 ImportSocket5 ImportSYS6 ImportOS7 8Server_address ='./test'9 Ten #first make sure that the file does not exist, but only for the local socket communication, if it already exists it is not possible One Try: AOs.unlink (server_address)#used to delete a file - exceptOSError: - ifos.path.exists (server_address): the Raise - -Sock =Socket.socket (Socket.af_unix,socket. SOCK_STREAM) - + Print>>sys.stderr,'starting up on%s'%server_address - Sock.bind (server_address) +Sock.listen (5) A at whileTrue: - Print>>sys.stderr,'waiting for a connection' -Connection,client_address =sock.accept () - Try: - Print>>sys.stderr,'Connection from', Client_address - whileTrue: indata = CONNECTION.RECV (16) - Print>>sys.stderr,'received "%s"'%Data to ifData: + Print>>sys.stderr,'sending data back to the client' - connection.sendall (data) the Else: * Print>>sys.stderr,'No data from', Client_address $ BreakPanax Notoginseng finally: -Connection.close ()
1 #!/usr/bin/python2 #Coding=utf-83 #Client4 ImportSocket5 ImportSYS6 7Sock =Socket.socket (Socket.af_unix,socket. SOCK_STREAM)8Server_address ='./test' #local socket traffic is set not by IP but by a file9 Ten Print>>sys.stderr,'Connection to%s'%server_address One A Try: - Sock.connect (server_address) - exceptsocket.error,msg: the Print>>sys.stderr,msg -Sys.exit (1) - - Try: +Message ='This is the message. It 'll be repeated' - Print>>sys.stderr,'sending "%s"'%message + sock.sendall (message) A atamount_received =0 -amount_expected =len (message) - - whileAmount_received <amount_expected: -data = SOCK.RECV (16) -Amount_received + =len (data) in Print>>sys.stderr,'received "%s"'%Data - finally: to Print>>sys.stderr,'Closing Socket' +Sock.close ()
Python-unix sockets