我可以将多个服务器绑定到同一个 TCP 端口吗? [英] Can I bind multiple servers to the same TCP port?

查看:73
本文介绍了我可以将多个服务器绑定到同一个 TCP 端口吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在同一个端口上有多个服务器会导致问题.事实上,当我尝试在同一端口上启动两台服务器时,我希望它抛出异常.问题是,在同一个端口上启动多个服务器似乎很高兴.我可以让以下代码的许多实例正常运行,无一例外.

I would expect having multiple servers on the same port would cause problems. In fact I want it to throw an exception when I try to start two servers on the same port. The problem is, it seems more than happy to start multiple servers on the same port. I can have many instances of the following code running just fine with no exceptions.

import BaseHTTPServer
import SimpleHTTPServer
import sys

def main():
    try:
        server = BaseHTTPServer.HTTPServer(('127.0.0.1',5000), SimpleHTTPServer.SimpleHTTPRequestHandler)
        print "On port: " + str(server.socket.getsockname()[1])
    except Exception, e:
        print e
    server.serve_forever()

if __name__ == "__main__":
    main()

所有这些都声称在端口 5000 上.如果它试图使用一个已经被占用的端口,我怎样才能让它抛出异常?

All of which claim to be on port 5000. How can I get it to throw an exception if it tries to use a port that is already taken?

这是 Python 2.6.4

This is Python 2.6.4

编辑 2:http://www.youtube.com/watch?v=rVOG3JdbHAM&feature=youtu.be 因为人们似乎认为我所解释的不可能?或者我完全误解了人们.无论哪种方式,这个视频都应该清除它.我启动了两台服务器,它们都没有打印出任何异常.当我关闭第一个时,第二个开始工作.为什么会这样?我希望第二台服务器永远不会启动并打印异常.这不是应该发生的事情吗?

Edit 2: http://www.youtube.com/watch?v=rVOG3JdbHAM&feature=youtu.be Because people seem to think what I am explaining is not possible? Or I am totally misunderstanding people. Either way, this video should clear it up. I start two servers, neither of them print out any exceptions. When I close the first, the second starts working. Why is this happening? I would expect the 2nd server to simply never start and print an exception. Is this not what should happen?

推荐答案

我试图执行你的代码并且第二个实例返回,

I tried to execute your code and the second instance returned,

 [Errno 98] Address already in use

应该的.SuSE Linux 上的 Python 2.6.

as it should. Python 2.6 on SuSE Linux.

可以用netstat工具检查5000端口是否真的被占用了?

Can check with netstat utility whether port 5000 is really taken?

这篇关于我可以将多个服务器绑定到同一个 TCP 端口吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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