且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python socket.error: [Errno 111] 连接被拒绝

更新时间:2022-05-02 08:10:02

问题显然是(如您所见)在您尝试连接时服务器端的端口 36250 未打开(因此连接被拒绝)).我可以看到服务器应该在另一个连接上收到 SEND 命令后打开这个套接字,但它显然没有与客户端同步打开 [它]".

The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND command on another connection, but it apparently was "not opening [it] up in sync with the client side".

嗯,主要原因是没有任何同步.调用:

Well, the main reason would be there was no synchronisation whatsoever. Calling:

cs.send("SEND " + FILE)
cs.close()

将数据放入操作系统缓冲区;close 可能会刷新数据并推送到网络中,但它几乎肯定会在数据到达服务器之前返回.在 close 之后添加 sleep 可能会缓解这个问题,但这不是同步.

would just place the data into a OS buffer; close would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep after close might mitigate the problem, but this is not synchronisation.

正确的解决方案是确保服务器已打开连接.这将需要服务器向您发送一些消息(例如 OK,或更好的 PORT 36250 以指示连接位置).这将确保服务器已经在监听.

The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK, or better PORT 36250 to indicate where to connect). This would make sure the server is already listening.

另一件事是您必须检查send 的返回值,以确保从缓冲区中取出了多少字节.或者使用 sendall.

(抱歉打扰了这个迟到的答案,但我发现这是一个高流量问题,我真的不喜欢评论部分中的睡眠想法.)

(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)