【发布时间】:2017-11-06 19:02:17
【问题描述】:
由于某种原因,下一个基本程序仅从第二次开始将客户端连接到服务器。所以每次重新启动服务器后。有人可以解释这种行为的原因以及如何解决这个问题吗?也许是因为 asyncore 只在服务器端使用? (Windows 7、Python 3)提前致谢!
客户:
import socket
sock = socket.socket()
host = 'localhost'
port = 8081
tempr = port
sock.connect((host,port))
服务器:
import asyncore
import socket
import time
class EchoHandler(asyncore.dispatcher_with_send):
def handle_read(self):
data = self.recv(1024)
class EchoServer(asyncore.dispatcher):
def __init__(self, host, port):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind((host, port))
self.listen(2)
def handle_accept(self):
pair = self.accept()
if pair is not None:
sock, addr = pair
print ('Incoming connection from %s' % repr(addr))
handler = EchoHandler(sock)
def main():
host = 'localhost'
port = 8081
server = EchoServer(host, port)
print ('Server %s running'% port)
asyncore.loop()
if __name__ == '__main__':
main()
【问题讨论】:
-
你得到什么错误?
-
没有错误也没有异常,但是handle_accept()函数只是从第二次尝试连接客户端开始执行。
-
我离开了文档,还不熟悉
asyncore,但我猜你不应该在handle_except中调用accept。服务器可能在接受连接后调用该函数,因此它是多余的。 -
这很奇怪。我从这里(从下面)获取服务器代码:docs.python.org/2/library/asyncore.html
标签: python python-3.x asynchronous server client