<p>我正在用Python编写telnet服务器。它是一个内容服务器。人们可以通过telnet连接到服务器,并且只显示文本内容。</p>
<p>我的问题是服务器显然需要支持多个同时连接。我现在的实现只支持一个。</p>
<p>这是我开始使用的基本的概念验证服务器(虽然程序随着时间的推移发生了很大的变化,但是基本的telnet框架没有):</p>
<pre><code>import socket, os
class Server:
def __init__(self):
self.host, self.port = 'localhost', 50000
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.bind((self.host, self.port))
def send(self, msg):
if type(msg) == str: self.conn.send(msg + end)
elif type(msg) == list or tuple: self.conn.send('\n'.join(msg) + end)
def recv(self):
self.conn.recv(4096).strip()
def exit(self):
self.send('Disconnecting you...'); self.conn.close(); self.run()
# closing a connection, opening a new one
# main runtime
def run(self):
self.socket.listen(1)
self.conn, self.addr = self.socket.accept()
# there would be more activity here
# i.e.: sending things to the connection we just made
S = Server()
S.run()
</code></pre>
<p>谢谢你的帮助。</p>