[英]Broken pipe error when trying to send data from server to client in Python sockets
I am trying to use "vanilla" Python sockets to transmit data from a server to a client, without using any asynchronous programming.我正在尝试使用“香草”Python sockets 将数据从服务器传输到客户端,而不使用任何异步编程。 My use case is the following: I would like a local Raspberry Pi to connect to my internet exposed server, and the server to send data through the created socket when a given event occurs.
我的用例如下:我希望本地 Raspberry Pi 连接到我的互联网公开服务器,并在给定事件发生时服务器通过创建的套接字发送数据。
I followed several tutorials on simple socket programming in Python to build the following code:我按照 Python 中的几个简单套接字编程教程构建了以下代码:
server.py
服务器.py
import socket
import time
def server():
PORT = 65432
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('0.0.0.0', PORT))
s.listen(1)
conn,address=s.accept() # accept an incoming connection using accept() method which will block until a new client connects
print("address: ", address[0])
time.sleep(5)
s.send("hey".encode())
conn.close()
return
server()
client.py
客户端.py
import socket
import time
HOST = "my.remote.domain"
PORT = 65432
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
while True :
print(s.recv(1024))
time.sleep(1)
When launching the server and the client on their respective machine, I can see that the connexion is correctly made, since the IP address of the client is printed in the logs of the server.在各自的机器上启动服务器和客户端时,我可以看到连接正确,因为客户端的 IP 地址打印在服务器的日志中。 However, after few seconds and before sending any data, I get the following error on the server side:
但是,几秒钟后,在发送任何数据之前,我在服务器端收到以下错误:
address: client_ip_address_appears_here
Traceback (most recent call last):
File "main.py", line 32, in <module>
receiver()
File "main.py", line 18, in receiver
s.send("heeey".encode())
BrokenPipeError: [Errno 32] Broken pipe
Meanwhile on the client side, no data is received:同时在客户端,没有收到数据:
b''
b''
b''
b''
b''
b''
b''
b''
b''
Is there a conceptual problem in the way I try to handle the socket?我尝试处理套接字的方式是否存在概念问题?
After trying out the code, I think the biggest problem you have is that the server is trying to send on the wrong socket.在尝试了代码之后,我认为您遇到的最大问题是服务器试图在错误的套接字上发送。 ie this line:
即这一行:
s.send("hey".encode())
should be rewritten like this:应该这样重写:
conn.send("hey".encode())
As it is, you are trying to send() on the TCP accepting-socket rather than on the TCP connection to the client, which doesn't make sense.实际上,您正在尝试在 TCP 接受套接字上而不是在与客户端的 TCP 连接上发送(),这没有意义。 On my (MacOS/X) system, the server process prints this error output:
在我的 (MacOS/X) 系统上,服务器进程打印此错误 output:
Jeremys-Mac-mini-2:~ jaf$ python server.py
('address: ', '127.0.0.1')
Traceback (most recent call last):
File "server.py", line 18, in <module>
server()
File "server.py", line 14, in server
s.send("hey".encode())
socket.error: [Errno 57] Socket is not connected
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.