server端:
if __name__ == '__main__': import socket,os,time sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('localhost', 8003)) sock.listen(5) print "\n this is Server:",time.strftime('%Y-%m-%d') while True: c,address = sock.accept() print "connection from:",address #connection.settimeout(10) while True: buf = c.recv(1024) if not buf: print address[0],"Client was off !" break tm=time.strftime('%H:%M:%S') print address[0],'@',tm,">",buf #cmd = os.popen(buf).read() while 1: cmd = raw_input("Server@"+time.strftime('%Y-%m-%d %H:%M:%S')+'#') if cmd =="":continue c.sendall(cmd) break sock.close()
client端:
if __name__ == '__main__': import socket,time sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('localhost',8003)) print "\n this is Client:",time.strftime('%Y-%m-%d') while True: c_input=raw_input("Client@"+time.strftime('%Y-%m-%d %H:%M:%S')+'#') if c_input=="":continue if c_input=="quit":break sock.sendall(c_input) data =sock.recv(1024) print 'Server@',time.strftime('%H:%M:%S'),">",data sock.close()
效果: