Multiple simultaneous network connections - Telnet

2020-05-25 08:03发布

I'm currently writing a telnet server in Python. It's a content server. People would connect to the server via telnet, and be presented with text-only content.

My problem is that the server would obviously need to support more than one simultaneous connection. The current implementation I have now supports only one.

This is the basic, proof-of-concept server I began with (while the program has changed greatly over time, the basic telnet framework hasn't):

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

Thanks for your help.

9条回答
乱世女痞
2楼-- · 2020-05-25 08:33

You need some form of asynchronous socket IO. Have a look at this explanation, which discusses the concept in low-level socket terms, and the related examples which are implemented in Python. That should point you in the right direction.

查看更多
Bombasti
3楼-- · 2020-05-25 08:34

For a really easy win implement you solution using SocketServer & the SocketServer.ThreadingMixIn

have a look a this echo server example it looks quite similar to what you're doing anyway: http://www.oreillynet.com/onlamp/blog/2007/12/pymotw_socketserver.html

查看更多
兄弟一词,经得起流年.
4楼-- · 2020-05-25 08:35

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

Testing:

$ 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.

Seriously, when it comes to asynchronous network, twisted is the way to go. It handles multiple connections in a single-thread single-process approach.

查看更多
一纸荒年 Trace。
5楼-- · 2020-05-25 08:36

Try MiniBoa server? It has exactly 0 dependencies, no twisted or other stuff needed. MiniBoa is a non-blocking async telnet server, single threaded, exactly what you need.

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

查看更多
ゆ 、 Hurt°
6楼-- · 2020-05-25 08:45

If you want to do it in pure python (sans-twisted), you need to do some threading. If you havnt seen it before, check out: http://heather.cs.ucdavis.edu/~matloff/Python/PyThreads.pdf

around page 5/6 is an example that is very relevant ;)

查看更多
迷人小祖宗
7楼-- · 2020-05-25 08:47

Late for the reply, but with the only answers being Twisted or threads (ouch), I wanted to add an answer for MiniBoa.

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

Twisted is great, but it's a rather large beast that may not be the best introduction to single-threaded asynchronous Telnet programming. MiniBoa is a lightweight, asynchronous single-threaded Python Telnet implementation originally designed for muds, which suits the OP's question perfectly.

查看更多
登录 后发表回答