Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple simultaneous network connections - Telnet server, Python

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.

like image 892
SpleenTea Avatar asked Apr 22 '09 08:04

SpleenTea


1 Answers

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.

like image 81
nosklo Avatar answered Sep 19 '22 14:09

nosklo