简体   繁体   English

适用于同一端口上的新客户端的Python更新TCP / IP套接字

[英]Python Update TCP/IP Socket for New Client on Same Port

I am working with a program that acts as a server, in that it receives a TCP/IP connection rather than making the connection. 我正在使用充当服务器的程序,因为它接收TCP / IP连接而不是建立连接。 When the program is started, I am able to open a TCP/IP port within the program and connect to it using: 程序启动后,我可以打开程序中的TCP / IP端口并使用以下命令连接到该端口:

import socket
s = socket.create_connection(("localhost",20100))
s.send("PAUSE\30")
s.recv(1024)

This will pause my program. 这将暂停我的程序。 I can continue to send commands in this fashion. 我可以继续以这种方式发送命令。 However, if I close the program, re-open the program, re-open the port in the program, and then try the same command, I receive: 但是,如果我关闭程序,重新打开程序,重新打开程序中的端口,然后尝试相同的命令,则会收到:

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

If I open a new port, say 20101, in the program and try to connect to it again, I receive: 如果我在程序中打开一个新端口,例如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

I have only been able to successfully reconnect if I restart the program, re-open the port, and restart my Python kernel. 只有重新启动程序,重新打开端口并重新启动Python内核后,我才能成功重新连接。

I would like to still communicate to the program after it is closed and re-opened without needing to restart my Python kernel. 在关闭并重新打开程序之后,我仍然想与程序通信,而无需重新启动Python内核。 Is it possible to do so? 有可能这样做吗? If not, why? 如果没有,为什么? If so, how could I augment my code to achieve this? 如果是这样,我该如何扩展我的代码来实现这一目标?

The problem I see there is the lack of s.close(). 我看到的问题是缺少s.close()。 You need to properly close the connection when you close or exit the program for the actual socket descriptor to be free. 关闭或退出程序时,需要正确关闭连接,以使实际的套接字描述符可用。 Are you calling that? 你打电话吗

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM