Server:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #coding=utf-8 import socket HOST='127.0.0.1' PORT=52314 s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.bind((HOST,PORT)) s.listen(1) while 1: conn,addr=s.accept() print 'The client on %s is connecting the server.' % str(addr) while 1: data=conn.recv(1024) if data=="\q": print 'The client is going to offline.' conn.close() break else: print data conn.close() s.close() |
Client:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #coding=utf-8 import socket HOST = '127.0.0.1' PORT = 52314 try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) while 1: cmd = raw_input() if cmd == "quit": print 'Bye!' s.sendall("\q") break s.sendall(cmd) finally: s.sendall("\q") s.close() |