Python 學習筆記: Socket 初步
阿新 • • 發佈:2018-11-22
Socket 初步
1 TCP chat server 程式:
import socket from socket import SOL_SOCKET,SO_REUSEADDR sk = socket.socket() # 設定socket的可選項, 允許port重複繫結,防止程式非正常推出時, 再次執行時作業系統尚未解除端口占用。 sk.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sk.bind(('127.0.0.1', 8090)) sk.listen() print('TCP chat Server is running...') conn, addr = sk.accept() print('%s user is connected...'%addr[0]) while True: content = conn.recv(1024).decode('utf-8') print(content) if content == 'bye': conn.send(b'bye') break info = input('>>>') conn.send(bytes(info, encoding='utf-8')) conn.close() sk.close()
TCP client 程式:
import socket sk = socket.socket() sk.connect(('127.0.0.1',8090)) sk.send(bytes('你好!', encoding='utf-8')) while True: ret = sk.recv(1024).decode('utf-8') print(ret) if ret == 'bye': sk.send(b'bye') break info = input('>>>') sk.send(bytes(info,encoding='utf-8')) sk.close()
2 UDP socket , chat server 舉例