python socket 客服端服务端编程
客服端编程
import socket try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error as msg: print(msg) exit() print('socket created') try: ip = socket.gethostbyname('www.baidu.com') except socket.gaierror as msg: print(msg) exit() print('host = ', ip) s.connect((ip, 80)) print('socket连接成功') try: msg = bytes("GET / HTTP/1.1\r\n\r\n", encoding='utf-8') s.sendall(msg) except socket.error: print('发送数据失败') exit() print('发送数据成功') while True: reply = s.recv(4096) if reply: print(reply) else: s.close() break
服务端socket编程
import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print('socket创建成功') try: s.bind(('', 888)) except socket.error as msg: print(msg) exit() print('socket绑定端口成功') s.listen(10) print('socket正在监听') while True: conn, addr = s.accept() print(addr[0]+'::'+addr[1], '客户端连接成功', ) data = conn.recv(1024) print('接收到的数据为',data) if not data: break conn.sendall(data) conn.close() s.close()