做一个很简单的client到server的socket收发。但是通讯一直有问题。检索了半天,换了n种方法就是收不到server的消息,经常莫名其妙[Errno 32] Broken pipe。
通过Stack Overflow的一个问题找到了答案:
server端,发送给client消息,使用的是accept()获取的client_socket,而不是监听端口的s。s没有连接任何东西,想从s发东西是不可能的,没有目标地址。因此server端只能从client_socket进行收发。
#接受客户端连接
client_socket,address = s.accept()
#打印客户端ip
print(f"客户端{address}已连接")
while True:
#接受客户端信息
received = client_socket.recv(BUFFER_SIZE).decode()
if received:
print("received:", received)
if received == 'end':
break
client_socket.send("pwd:1234".encode())
原问题:python-socket-error-errno-32-broken-pipe
回答:
c, addr = s.accept()
s.send("welcome !")
The listener (s) is not connected to anything which means any attempts to use it for sending will fail because there is no destination known for the data. One can only send data on a connected socket (c), i.e. the one returned from accept.
附上完整代码:
client:
import socket
#服务器信息
HOST = "yourHost"
PORT = 7700
ADDR = (HOST,PORT)
#缓冲区
BUFFER_SIZE = 4096
s = socket.socket()
print(f"服务器连接中{HOST}:{PORT}")
#连接服务器
s.connect(ADDR)
print("服务器连接成功")
s.send("hellloo".encode())
while True:
data = s.recv(BUFFER_SIZE)
if data :
print('data:', data)
s.send("end".encode())
break
print("已断开连接!")
s.close()
server:
import socket
import random
SERVER_HOST = ''
SERVER_PORT = 7700
BUFFER_SIZE = 4096
ADDR = (SERVER_HOST,SERVER_PORT)
#创建server
s = socket.socket()
s.bind(ADDR)
#设置连接监听数
s.listen(5)
print(f"服务器监听{SERVER_HOST}:{SERVER_PORT}")
while True:
print("等待客户端连接...")
#接受客户端连接
client_socket,address = s.accept()
#打印客户端ip
print(f"客户端{address}已连接")
while True:
#接受客户端信息
received = client_socket.recv(BUFFER_SIZE).decode()
if received:
print("received:", received)
if received == 'end':
break
client_socket.send("pwd:1234".encode())
print('关闭客户端连接')
#关闭资源
client_socket.close()
s.close()