import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 創建鏈接: s.connect(('127.0.0.1', 5500)) # 接收歡迎消息: print(s.recv(1024).decode('utf-8')) for data in [b'Michael', b'Tracy', b'Sarah']: # 發送數據: s.send(data) print(s.recv(1024).decode('utf-8')) s.send(b'exit') # 關閉鏈接 s.close()
import socket import threading # 處理tcp 鏈接 def tcp_link(sock, addr): print(addr) # 打印鏈接信息 print('link create, from %s:%s' % addr) # 鏈接創建後發送歡迎信息 sock.send(b'Welcome!') while True: data = sock.recv(1024) # 若是信息爲空或信息爲exit,則退出鏈接 if not data or data.decode('utf-8') == 'exit': break sock.send(('hello, %s' % data.decode('utf-8')).encode('utf-8')) sock.close() print('link close, from %s:%s' % addr) # 以ipv4, 流媒體建立socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 監聽端口: s.bind(('127.0.0.1', 5500)) # 限制最大鏈接數爲5個 s.listen(5) while True: # 接受新鏈接 sock, addr = s.accept() # 建立新線程來處理TCP鏈接,否者會堵塞其餘用戶的請求 t = threading.Thread(target=tcp_link, args=(sock, addr)) t.start()