伺服器端:
#!/usr/bin/pythonimport socketfrom time import ctimeimport sysbufsize = 1024host = '127.0.0.1'port = 8100address = (host,port)server_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)server_sock.bind(address)server_sock.listen(1)while True:print 'waiting for connection...'clientsock,addr = server_sock.accept()print 'received from :',addrwhile True:data = clientsock.recv(bufsize)print '%s\n%s' %(ctime(),data)data = raw_input(">")clientsock.send(data)clientsock.close()server_sock.close()
用戶端:
#!/usr/bin/pythonfrom socket import *from time import ctimeimport sysbufsize = 1024host = sys.argv[1]port = int(sys.argv[2])addr = (host,port)client_sock = socket(AF_INET,SOCK_STREAM)client_sock.connect(addr)while True:data = raw_input(">")if not data:breakelse:client_sock.send(data)data = client_sock.recv(bufsize)print '%s\n%s' %(ctime(),data)client_sock.close()