问题
I'm trying to deploy a python socket server to Heroku, but it seems that the socket connection is not well made... In my case, the accept() method should wait for a socket connection to be made, but it seems that it fires even if I don't run my client.py script...
Also, when running the client, the connection is indeed made, but the server doesn't receive nor send any data...
What am I doing wrong? All of this works locally... (changing the port from 80 to 12345 and the address to localhost)...
Here's what I have so far :
# server.py
import socket
import os
server = socket.socket()
port = int(os.environ.get("PORT", 12345))
server.bind(("0.0.0.0", port))
server.listen(5)
# should wait for an actual connection, but fires right away
s, _ = server.accept()
# should wait to receive "Hello, world! (from client)", but receives b''
s.recv(1024)
s.send("Hello, world! (from server)".encode())
s.close()
# client.py
import socket
s = socket.socket()
print("connecting to server...")
# "...my-heroku-app.." changed to the actual heroku app url
s.connect(("my-heroku-app.herokuapp.com", 80))
print("sending data...")
s.send("Hello, world! (from client)".encode())
print("receiving data...")
# should receive "Hello, world! (from server)",
# but blocks because the server already stopped
print(s.recv(1024).decode())
s.close()
# Procfile
web: python server.py
I've also tried to put the s.recv() in a loop until data received is not None, but that just loops forever... (on the server side)
What am I doing wrong here? Is the server binding (address and port) correct? Does Heroku support that kind of server? I don't seem to find any info about how to do it (there only are examples using Flask and other web-servers frameworks...).
EDIT
After some logging, it seems that 172.18.17.53 is the IP that always connects to the server and keeps it busy. It also seems that this IP is unreachable because the send() function blocks...
I've tried to add s.settimeout(0.05) but it changed nothing for the send() method...
来源:https://stackoverflow.com/questions/54164238/heroku-python-socket-connection-fails