如何在Python中使用套接字创建通道

用户名

我已经数次启动了Python,现在,我正在创建一个套接字服务器。我已经使服务器与具有多个客户端的多个线程一起工作(万岁!),但是我正在寻找无法调用的功能(我什至不知道它是否存在)我想在客户端创建一种渠道可以发送不同类型的消息。

我创建一个通道INFO的示例,如果服务器接收到这种类型的套接字,它只会执行打印

我创建了另一个通道DEBUG,可以在其中发送服务器将执行的自定义命令

等等

使用非编程语言,它将执行以下操作:

def socketDebug(command):
     run command

def socketInfo(input):
     print input

if socket == socketDebug:
     socketDebug(socket.rcv)
else:
   if socket == socketInfo:
     socketInfo(socket.rcv)

我希望我很清楚。

姆吉耶尔

这是Channel类的一个非常简单的实现。它创建一个套接字,以接受来自客户端的连接并发送消息。它本身也是一个客户端,从其他Channel实例接收消息(例如,在单独的进程中)。

通信是在两个线程中完成的,这非常糟糕(我将使用async io)。收到消息后,它将在接收线程中调用已注册的函数这可能会导致某些线程问题。

每个Channel实例都创建自己的套接字,但是通过单个实例多路复用通道“主题”将具有更大的可伸缩性。

一些现有的库提供了“通道”功能,例如nanomsg

如果可以的话,此处的代码用于教育目的...

import socket
import threading

class ChannelThread(threading.Thread):
  def __init__(self):
    threading.Thread.__init__(self)

    self.clients = []
    self.chan_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    self.chan_sock.bind(('',0))  
    _, self.port = self.chan_sock.getsockname()
    self.chan_sock.listen(5)
    self.daemon=True
    self.start()

  def run(self):
    while True:
      new_client = self.chan_sock.accept()
      if not new_client:
        break
      self.clients.append(new_client)

  def sendall(self, msg):
    for client in self.clients:
      client[0].sendall(msg)

class Channel(threading.Thread):
  def __init__(self):
    threading.Thread.__init__(self)

    self.daemon = True
    self.channel_thread = ChannelThread()

  def public_address(self):
    return "tcp://%s:%d" % (socket.gethostname(), self.channel_thread.port)

  def register(self, channel_address, update_callback):
    host, s_port = channel_address.split("//")[-1].split(":")
    port = int(s_port)
    self.peer_chan_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)   
    self.peer_chan_sock.connect((host, port))
    self._callback = update_callback
    self.start()

  def deal_with_message(self, msg):
    self._callback(msg)

  def run(self):
    data = ""
    while True:
      new_data = self.peer_chan_sock.recv(1024)
      if not new_data:
        # connection reset by peer
        break
      data += new_data
      msgs = data.split("\n\n")
      if msgs[-1]:
        data = msgs.pop()
      for msg in msgs:
        self.deal_with_message(msg)

  def send_value(self, channel_value):
    self.channel_thread.sendall("%s\n\n" % channel_value)

用法:

在过程A中:

c = Channel()
c.public_address()

在过程B中:

def msg_received(msg):
  print "received:", msg

c = Channel()
c.register("public_address_string_returned_in_process_A", msg_received)

在过程A中:

c.send_value("HELLO")

在过程B中:

received: HELLO

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章