服务器
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | #encoding=utf-8 import sys import socket def start_tcp_server(ip, port):     # create socket     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)     server_address = (ip, port)     # bind port     print 'starting listen on ip %s, port %s' % server_address     sock.bind(server_address)     # starting listening, allow only one connection     try:         sock.listen(1)     except socket.error, e:         print "fail to listen on port %s" % e         sys.exit(1)     while True:         print "waiting for connection"         client, addr = sock.accept()         print 'having a connection'         client.send('>')         while True:             try:                 s = client.recv(255)             except:                 print "disconnected."                 print "waiting for connection"                 client, addr = sock.accept()                 print 'having a connection'                 s = client.recv(255)             if s:                 s = s.strip()                 print ( 'receive %s' % s)                     client.send('>')             else:                 print "disconnected."                 print "waiting for connection"                 client, addr = sock.accept()                 print 'having a connection' if __name__ == '__main__':     start_tcp_server('127.0.0.1', 8000) | 
客户端
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #encoding=utf-8 import socket HOST = '127.0.0.1'  PORT = 8000  with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:     s.connect((HOST, PORT))     p = input('send:')      s.sendall(p.encode('utf-8'))     data = s.recv(1024)     print(data)     s.shutdown(0)     s.close() | 
