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

Spl*_*Tea 16 python sockets telnet

我目前正在用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()
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助.

nos*_*klo 16

扭曲实施:

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()
Run Code Online (Sandbox Code Playgroud)

测试:

$ 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.
Run Code Online (Sandbox Code Playgroud)

说真的,谈到异步网络,扭曲是可行的方法.它以单线程单进程方法处理多个连接.


Tre*_*out 2

如果您面临一些概念上的挑战,我会考虑使用twisted。

您的案例作为twisted 的一部分实施起来应该很简单。 http://twistedmatrix.com/projects/core/documentation/howto/servers.html