套接字通信底层原理
套接字通信底层原理
由应用程序内存拷贝到操作系统,操作系统遵循TCP协议向对方去发,对方接收到并发送信号
from socket import * client = socket(AF_INET, SOCK_STREAM) client.connect(('127.0.0.1', 8081)) # 通信循环 while True: msg=input('>>: ').strip() #msg='' if len(msg) == 0:continue client.send(msg.encode('utf-8')) #client.send(b'') print('has send') data=client.recv(1024) print('has recv') print(data) client.close()
# 服务端必须满足至少三点: # 1. 绑定一个固定的ip和port # 2. 一直对外提供服务,稳定运行 # 3. 能够支持并发 from socket import * server = socket(AF_INET, SOCK_STREAM) server.bind(('127.0.0.1', 8081)) server.listen(5) # 链接循环 while True: conn, client_addr = server.accept() print(client_addr) # 通信循环 while True: try: data = conn.recv(1024) if len(data) == 0: break # 针对linux系统 print('-->收到客户端的消息: ', data) conn.send(data.upper()) except ConnectionResetError: break conn.close() server.close()