TCP编程-- server
1 import socket, threading, time 2 3 def dealClient(sock, addr): 4 print('Accept new connection from %s:%s...' % addr) 5 sock.send(b'Hello, I am server!') # 给client端发送数据 6 while True: 7 data = sock.recv(1024) # 接收client发过来的数据 8 time.sleep(1) 9 if not data or data.decode('utf-8') == 'exit': 10 break 11 print('-->> %s !' % data.decode('utf-8')) 12 sock.send(('Loop_Msg: %s !' % data.decode('utf-8')).encode()) # 发送数据给client 13 sock.close() 14 print('Connection from %s:%s closed' % addr) 15 16 if __name__ == '__main__': 17 # 创建socket并绑定IP 18 s = socket.socket() 19 s.bind(('127.0.0.1', 9999)) 20 s.listen() # 启用监听 21 print('Waiting for connection...') 22 while True: 23 sock, addr = s.accept() # 接收一个新的连接 24 t = threading.Thread(target = dealClient, args = (sock, addr)) #创建新的线程来处理TCP连接 25 t.start()
TCP编程-- client
1 import socket 2 3 s = socket.socket() 4 s.connect(('127.0.0.1', 9999)) # 建立连接 5 print('-->>' + s.recv(1024).decode('utf-8')) # 接收消息 6 s.send(b'Hello, I am a client') 7 print('-->>' + s.recv(1024).decode('utf-8')) 8 s.send(b'exit') # 发送消息 9 s.close()
代码摘自 Python爬虫开发与项目实战-- 机械工业出版社