簡體   English   中英

多個同時網絡連接 - Telnet服務器,Python

[英]Multiple simultaneous network connections - Telnet server, 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()

謝謝你的幫助。

扭曲實施:

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.

說真的,談到異步網絡,扭曲是可行的方法。 它以單線程單進程方法處理多個連接。

答案遲到,但唯一的答案是扭曲或線程(哎喲),我想為MiniBoa添加一個答案。

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

扭曲是偉大的,但它是一個相當大的野獸,可能不是單線程異步Telnet編程的最佳介紹。 MiniBoa是一個輕量級的異步單線程Python Telnet實現,最初是為泥漿設計的,完全符合OP的問題。

您需要某種形式的異步套接字IO。 看一下這個解釋 ,它討論了低級套接字術語中的概念,以及用Python實現的相關示例。 這應該指向正確的方向。

對於一個非常簡單的win,使用SocketServer和SocketServer.ThreadingMixIn實現解決方案

看看這個echo服務器示例,它看起來非常類似於你正在做的事情: http//www.oreillynet.com/onlamp/blog/2007/12/pymotw_socketserver.html

如果你有一些概念上的挑戰,我會考慮使用twisted。

作為扭曲的一部分,你的案例應該是微不足道的。 http://twistedmatrix.com/projects/core/documentation/howto/servers.html

使用線程,然后將處理程序添加到函數中。 每次發出請求時,線程都會調用:

看這個

 import socket               # Import socket module
import pygame
import thread
import threading,sys

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.
s.bind((host, port))
print ((host, port))
name = ""
users = []

def connection_handler (c, addr):
      print "conn handle"
      a = c.recv (1024)
      if a == "c":
         b = c.recv (1024)
      if a == "o":
         c.send (str(users))
         a = c.recv (1024)
         if a == "c":
            b = c.recv (1024)
      print a,b






s.listen(6)                 # Now wait for client connection.
while True:
   c, addr = s.accept()
   print 'Connect atempt from:', addr[0]
   username = c.recv(1024)
   print "2"
   if username == "END_SERVER_RUBBISH101":
      if addr[0] == "192.168.1.68":
         break
   users.append(username)
   thread.start_new_thread (connection_handler, (c, addr)) #New thread for connection

print 
s.close()

試試MiniBoa服務器? 它有0個依賴項,不需要扭曲或其他東西。 MiniBoa是一個非阻塞的異步telnet服務器,單線程,正是你需要的。

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

如果你想用純python(sans-twisted)來做,你需要做一些線程。 如果你以前看過它,請查看: http ://heather.cs.ucdavis.edu/~matloff/Python/PyThreads.pdf

第5/6頁左右是一個非常相關的例子;)

首先,購買Comer關於TCP / IP編程的書籍。

在這些書中,Comer將為服務器提供幾種替代算法。 有兩種標准方法。

  • 線程每個請求。

  • 過程的每次請求。

您必須從中選擇其中一個並實現它。

在thread-per中,每個telnet會話都是整個應用程序中的一個單獨的線程。

在process-per中,您將每個telnet會話分成一個單獨的子進程。

您會發現在Python中處理每個請求的過程要容易得多,而且通常可以更有效地使用您的系統。

每個請求的線程適用於快速進出的事情(如HTTP請求)。 Telnet具有長時間運行的會話,其中子進程的啟動成本不會影響性能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM