0

试图创建一个线程化的 http 服务器。当我通过网络浏览器连接到该服务器时,虽然我只能在服务器停止之前拉起一件事。发生这种情况有什么特别的原因吗?

import socket
from threading import Thread
class http():
    def __call__():
        return 0
    def site(self):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.bind(("localhost", 5124))
            s.listen(2)
        except socket.error, (value,message):
            if s:
                s.close()
                return 2
        c, addr = s.accept()
        s = c.recv(1024)
        print s
        c.send("test")
        c.close()
        return s

serve = http()

def happy():
    while True:
        serve.site()

if __name__ == '__main__':
    Thread(target = happy()).start()
4

2 回答 2

1

尝试 target=happy,不带括号。

于 2013-01-15T16:27:20.573 回答
1

The problem comes when the connection is closed and you try to reconnect before the socket leave the TIME_WAIT state. Try using the socket.SO_REUSEADDR socket option or use a random port every time.

import socket


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("localhost", 1234))
s.listen(2)
print 'listening on port %s' % s.getsockname()[1]
while True:
    c, addr = s.accept()
    buf = c.recv(1024)
    c.send(buf)
    c.close()
于 2013-01-15T17:01:36.800 回答