Python更新同一端口上的新客户端的TCP/IP套接字
问题描述:
我正在使用充当服务器的程序,因为它接收TCP/IP连接而不是进行连接。当程序开始时,我能打开程序中的TCP/IP端口,并使用连接到它:Python更新同一端口上的新客户端的TCP/IP套接字
import socket
s = socket.create_connection(("localhost",20100))
s.send("PAUSE\30")
s.recv(1024)
这将暂停我的程序。我可以继续以这种方式发送命令。不过,如果我关闭程序,重新打开该程序,重新打开端口的程序,然后尝试相同的命令,我收到:
s.send("PAUSE\30")
s.recv(1024)
---------------------------------------------------------------------------
error Traceback (most recent call last)
<ipython-input-7-40f527ce990f> in <module>()
1 s.send("PAUSE\30")
----> 2 s.recv(1024)[1:-1]
error: [Errno 10053] An established connection was aborted by the software in your host machine
如果我打开一个新的端口,比如20101,在节目中,并尝试重新连接到它,我得到:
s = socket.create_connection(("localhost",20101))
---------------------------------------------------------------------------
error Traceback (most recent call last)
<ipython-input-8-857374ef86d3> in <module>()
----> 1 s = socket.create_connection(("localhost",20101))
C:\Program Files\Enthought\Canopy\App\appdata\canopy-1.5.5.3123.win-x86_64\lib\socket.pyc in create_connection(address, timeout, source_address)
569
570 if err is not None:
--> 571 raise err
572 else:
573 raise error("getaddrinfo returns an empty list")
error: [Errno 10061] No connection could be made because the target machine actively refused it
我只能够当我重新启动该程序,重新打开端口成功重新连接,并重新启动我的Python内核。
我想在程序关闭并重新打开后仍然可以与程序通信,而无需重新启动我的Python内核。是否有可能这样做?如果不是,为什么?如果是这样,我如何增加我的代码来实现这一目标?
答
我在那里看到的问题是缺少s.close()。当您关闭或退出程序时,您需要正确关闭连接以使实际套接字描述符空闲。你在打电话吗?
您的服务器能够一次接受多个连接吗?客户端断开连接时是否正确关闭连接?显示您的服务器代码或显示问题的[MCVE](http://stackoverflow.com/help/mcve)。 – mhawke