Python服务器“通常仅允许每个套接字地址的一次使用” [英] Python server "Only one usage of each socket address is normally permitted"

查看:1689
本文介绍了Python服务器“通常仅允许每个套接字地址的一次使用”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Python中创建一个非常基本的服务器在一个端口上侦听,创建一个TCP连接,当客户端尝试连接,接收数据,发送回来,然后再次监听(并无限期重复该过程) 。这是我到目前为止:

 从套接字import * 

serverName =localhost
serverPort = 4444
BUFFER_SIZE = 1024

s = socket(AF_INET,SOCK_STREAM)
s.bind((serverName,serverPort))
s.listen 1)

print服务器已准备好接收数据...

while 1:
newConnection,client = s.accept()
msg = newConnection.recv(BUFFER_SIZE)

打印msg

newConnection.send(hello world)
newConnection.close()
<有时这似乎工作得很好(如果我将浏览器指向localhost:4444服务器打印出HTTP GET请求并且网页打印文本hello world)。但是,当我在最近几分钟关闭服务器后尝试启动服务器时,偶尔会出现以下错误消息:

 跟踪(最近最后调用):
文件path\server.py,第8行,在< module>
s.bind((serverName,serverPort))
文件C:\Python27\lib\socket.py,第224行,在meth
中return getattr(self._sock ,name)(* args)
错误:[Errno 10048]通常允许每个套接字地址(协议/网络地址/端口)只使用一次

我使用Windows 7在python中编程。有关如何修复此问题的任何想法?

解决方案

在调用bind()之前启用 SO_REUSEADDR 套接字选项。这允许地址/端口立即被重用,而不是在TIME_WAIT状态中停留几分钟,等待后来的数据包到达。

  s.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)


I'm trying to create a very basic server in python that listens in on a port, creates a TCP connection when a client tries to connect, receives data, sends something back, then listens again (and repeats the process indefinitely). This is what I have so far:

from socket import *

serverName = "localhost"
serverPort = 4444
BUFFER_SIZE = 1024

s = socket(AF_INET, SOCK_STREAM)
s.bind((serverName, serverPort))
s.listen(1)

print "Server is ready to receive data..."

while 1:
        newConnection, client = s.accept()
        msg = newConnection.recv(BUFFER_SIZE)

        print msg

        newConnection.send("hello world")
        newConnection.close()

Sometimes this seems to work perfectly well (if I point my browser to "localhost:4444" the server prints out the HTTP GET request and the webpage print the text "hello world"). But I'm getting the following error message sporadically when I try to start the server after closing it in the last few minutes:

Traceback (most recent call last):
  File "path\server.py", line 8, in <module>
    s.bind((serverName, serverPort))
  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

I'm programming in python using Windows 7. Any ideas on how to fix this?

解决方案

Enable the SO_REUSEADDR socket option before calling bind(). This allows the address/port to be reused immediately instead of it being stuck in the TIME_WAIT state for several minutes, waiting for late packets to arrive.

s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)

这篇关于Python服务器“通常仅允许每个套接字地址的一次使用”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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