python websocket与龙卷风.插座未关闭 [英] python websocket with tornado. Socket aren't closed

查看:122
本文介绍了python websocket与龙卷风.插座未关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是websocket的初学者,我正试图将龙卷风用于此目的.到目前为止,这是我的工作代码:

I'm a beginner with websocket, I'm trying to use tornado for that purpose. Here is my working code so far:

from tornado import websocket
from tornado import web
import tornado.ioloop

class EchoWebSocket(websocket.WebSocketHandler):
    def open(self):
        print "WebSocket opened"

    def on_message(self, message):
        self.write_message(u"You said: " + message)
        print message

    def on_close(self):
        print "WebSocket closed"

    def check_origin(self, origin):
        return True

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")

application = tornado.web.Application([(r"/", EchoWebSocket),(r'/',MainHandler),])
application.listen(8001)
tornado.ioloop.IOLoop.instance().start()

我正在使用IDLE,到目前为止一切正常,只有一个烦人的问题.我无法修复此代码,只能重新运行服务器,而不会看到此错误:

I'm using IDLE, and everything is working fine so far, only one annoying problem. I can't fix this code and than re-run the server without seeing this error:

    application.listen(8001)
  File "C:\Python27\lib\site-packages\tornado\web.py", line 1691, in listen
    server.listen(port, address)
  File "C:\Python27\lib\site-packages\tornado\tcpserver.py", line 125, in listen
    sockets = bind_sockets(port, address=address)
  File "C:\Python27\lib\site-packages\tornado\netutil.py", line 137, in bind_sockets
    sock.bind(sockaddr)
  File "C:\Python27\lib\socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
error: [Errno 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted

当我终止程序时,python似乎没有关闭套接字.我发现的唯一方法是终止任务管理器中的python进程,而不是让端口再次空闲".
为什么会发生这种情况,并且可以采取什么措施(确实很难做到这一点..)?为什么OS无法释放我的端口?

It seems that python doesn't close the socket when I terminate the program. The only way I found is to terminate the python process in task manager, than I have my port 'free' again.
Why this is happening, and what can be done (it's really hard working like that..)? Why OS won't free the my port ?

推荐答案

您需要停止服务器,以便该端口可以再次使用.

You need to stop the server so that the port is available for use again.

这将停止服务器:

tornado.ioloop.IOLoop.instance().stop()

您应该在服务器运行完毕后调用(如果使用CTRL-C将其杀死,则需要捕获并在处理程序中调用它).

You should call when you are done running the server (if you kill it with CTRL-C, you need to catch that and call this in the handler).

您可以使用以下命令捕获CTRL-C:

You can catch CTRL-C with this:

import signal
def signal_handler(signum, frame):
    tornado.ioloop.IOLoop.instance().stop()

signal.signal(signal.SIGINT, signal_handler)

这篇关于python websocket与龙卷风.插座未关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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