server
# -*- coding: utf-8 -*-"""Created on Mon Mar 28 22:28:29 2016@author: zhanghc"""#引入模块import socketimport threadingimport timedef tcplink(sock,addr): print('Accept new connection from {0}:{0}...'.format(addr)) sock.send('Welcome!') while True: data=sock.recv(1024) time.sleep(1) if data=='exit' or not data: break sock.send('Hello,%s!'%data) sock.close() print('Connection from {0}:{0} closed'.format(addr))#创建sockets=socket.socket(socket.AF_INET,socket.SOCK_STREAM)#监听端口s.bind(('127.0.0.1',9999))s.listen(5)print('Waiting for connection...')while True: #接受一个新连接 sock,addr=s.accept() #创建新线程来处理TCP连接 t=threading.Thread(target=tcplink(sock,addr))
输出:
Waiting for connection...Accept new connection from ('127.0.0.1', 53535):('127.0.0.1', 53535)...Connection from ('127.0.0.1', 53535):('127.0.0.1', 53535) closed
client
# -*- coding: utf-8 -*-"""Created on Mon Mar 28 22:40:41 2016@author: zhanghc"""import sockets=socket.socket(socket.AF_INET,socket.SOCK_STREAM)s.connect(('127.0.0.1',9999))print(s.recv(1024))for data in ['zhang','liu','wang']: s.send(data) print(s.recv(1024))s.send('exit')s.close()
输出:
Welcome!Hello,zhang!Hello,liu!Hello,wang!