多个同时网络连接 - Telnet 服务器,Python [英] Multiple simultaneous network connections - Telnet server, Python

查看:28
本文介绍了多个同时网络连接 - Telnet 服务器,Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在用 Python 编写一个 telnet 服务器.这是一个内容服务器.人们将通过 telnet 连接到服务器,并看到纯文本内容.

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.

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

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

感谢您的帮助.

推荐答案

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 是要走的路.它以单线程单进程的方式处理多个连接.

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

这篇关于多个同时网络连接 - Telnet 服务器,Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆