多个同时的网络连接-Telnet服务器,Python

2024-05-16 01:52:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python编写telnet服务器。它是一个内容服务器。人们可以通过telnet连接到服务器,并且只显示文本内容。

我的问题是服务器显然需要支持多个同时连接。我现在的实现只支持一个。

这是我开始使用的基本的概念验证服务器(虽然程序随着时间的推移发生了很大的变化,但是基本的telnet框架没有):

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()

谢谢你的帮助。


Tags: runself服务器sendhost内容serverport
3条回答

回信迟了,但由于唯一的答案是扭曲或线程(哎哟),我想添加一个MiniBoa的答案。

http://code.google.com/p/miniboa/

Twisted很棒,但它是一个相当大的野兽,可能不是单线程异步Telnet编程的最佳入门。MiniBoa是一个轻量级的异步单线程Python Telnet实现,最初是为muds设计的,非常适合OP的问题。

twisted中实现:

from twisted.internet.protocol import Factory, Protocol
from twisted.internet import reactor

class SendContent(Protocol):
    def connectionMade(self):
        self.transport.write(self.factory.text)
        self.transport.loseConnection()

class SendContentFactory(Factory):
    protocol = SendContent
    def __init__(self, text=None):
        if text is None:
            text = """Hello, how are you my friend? Feeling fine? Good!"""
        self.text = text

reactor.listenTCP(50000, SendContentFactory())
reactor.run()

测试:

$ telnet localhost 50000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Hello, how are you my friend? Feeling fine? Good!
Connection closed by foreign host.

说真的,在异步网络方面,twisted是一个不错的选择。它以单线程单进程的方式处理多个连接。

您需要某种形式的异步套接字IO。看看this explanation,它讨论了底层套接字术语中的概念,以及用Python实现的相关示例。这应该会给你指明正确的方向。

相关问题 更多 >