Stakeoverflow相关问题链接:https://stackoverflow.com/questions/16130786/why-am-i-getting-the-error-connection-refused-in-python-sockets

解决方案

Instead of

host = socket.gethostname() #Get the local machine name
port = 12397 # Reserve a port for your service
s.bind((host,port)) #Bind to the port

you should try

port = 12397 # Reserve a port for your service
s.bind(('', port)) #Bind to the port

so that the listening socket isn’t too restricted. Maybe otherwise the listening only occurs on one interface which, in turn, isn’t related with the local network.

One example could be that it only listens to 127.0.0.1, which makes connecting from a different host impossible.

意思就是如果bind方法里的第一个参数写的是127.0.0.1,那么就只能监听从127.0.0.1发送过来的数据。

解决方案:第一个参数留成空白字符串就可以解决端口访问不到的问题了。

Q.E.D.