Python套接字无法正确关闭连接 [英] Python socket doesn't close connection properly

查看:72
本文介绍了Python套接字无法正确关闭连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是套接字编程的新手,但遇到一个令人困惑的问题:

I am new to socket programming and ran into a puzzling problem:

我有一个Windows程序,该程序无法更改(专有软件),但尝试使用TCP套接字连接到特定的IP和端口.

I have a windows program which I cannot alter (proprietary software) but which tries to connect to a specific ip and port with a tcp socket.

在我的Linux机器上,我写了一个小python脚本来为win prog提供套接字.直到我在Linux上杀死我的编程序,它才能正常工作.初始服务器套接字未按指定关闭,并且直到该套接字被垃圾回收后,我才能重新启动程序.

On my linux box I wrote a little python script to serve the socket to the win prog. This works fine until I kill my prog on linux. The initial server socket doesn't close as specified and I cannot restart my program until the socket is garbage collected.

如果我使用linux套接字(在单独的python脚本中)尝试相同的操作,则没有问题.

If I try the same with a linux socket (in a seperate python script) I have no problems.

这是一个最小的代码示例:

Here is a minimal code example:

import socket

server = socket.socket()
server.bind(('192.168.0.111', 50001))
server.listen(1)
conn, addr = server.accept()
print 'Connection established'

running = True
while running:
    try:
        data = conn.recv(4096)
    except KeyboardInterrupt:
        conn.close()
        running = False
    else:
        if data:
            print data
        else:
            conn.close()
            running = False
server.close()

如果我用Ctrl-C杀死了它,它将正常退出.但是重新启动脚本后,我收到一个socket.error,指出该地址已在使用中.大约一分钟后,该程序将再次运行.

If I kill this with Ctrl-C it exits normally. But upon restarting the script I get a socket.error stating the address is already in use. After a minute or so the program works again.

我还尝试在关闭之前关闭计算机(又名conn.shutdown(2)和server.shutdown ...),但这没有任何作用.

I also tried a shutdown before the close (aka conn.shutdown(2) and server.shutdown...) but that has no effect.

是否有更好的正确"方式关闭Windows套接字?我是否会错过有关套接字的一些基本知识?

Is there a better 'right' way to close a windows socket? Do I miss something fundamental about sockets in general?

谢谢!

edit:我想我刚刚在这里看到了答案:什么是正确的方法在python 2.6中关闭套接字?

edit: I think I just saw the answer here: what is the correct way to close a socket in python 2.6?

尽管我使用的是python 2.5,但仍可以使用.

Although I'm using python 2.5 it might still work.

推荐答案

您正在体验已连接套接字的 TIME_WAIT 状态.即使您已关闭插槽,它仍然会持续挥霍几分钟. UNIX指南套接字常见问题解答.

You are experiencing the TIME_WAIT state of connected sockets. Even though you've closed your socket, it still has lingering consequences for a couple minutes. The reasons for this, as well as a socket flag you can set to disable the behavior (SO_REUSEADDR), are explained in the UNIX guide socket FAQ.

简而言之,

server = socket.socket()
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(...)
...

这篇关于Python套接字无法正确关闭连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆