Socket Basics
erhuabushuo
posted @ 2012年5月23日 15:23
in Python
, 1243 阅读
server
from socket import * myHost = '' myPort = 50007 sockobj = socket(AF_INET, SOCK_STREAM) sockobj.bind((myHost, myPort)) sockobj.listen(5) while True: connection, address = sockobj.accept() print('Server connected by', address) while True: data = connection.recv(1024) if not data: break connection.send(b'Echo=>' + data) connection.close()
client
import sys from socket import * serverHost = 'localhost' serverPort = 50007 message = [b'Hello network world'] if len(sys.argv) > 1: serverHost = sys.argv[1] if len(sys.argv) > 2: message = (x.encode() for x in sys.argv[2:]) sockobj = socket(AF_INET, SOCK_STREAM) sockobj.connect((serverHost, serverPort)) for line in message: sockobj.send(line) data = sockobj.recv(1024) print('Client received:', data) sockobj.close()