如何在Python中使用socket创建信道

2024-10-01 16:42:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经在几天前启动了Python,现在,我正在创建一个socket服务器。在

我已经有了多线程多客户机的服务器功能(Huray!)在

但我正在寻找一个我不能调用的函数(我甚至不知道它是否存在)

我想创建一种渠道,客户可以发送不同类型的消息。在

示例我创建一个频道信息,如果服务器接收到这种类型的套接字,它只需打印

我创建另一个通道调试,在那里我可以发送服务器将执行的自定义命令

等等

在非编程语言中,它将执行以下操作:

def socketDebug(command):
     run command

def socketInfo(input):
     print input

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

我希望我是清楚的,因为我不是英国人。在

提前感谢您的帮助!在

:-)


Tags: 函数功能服务器类型input客户机ifdef
1条回答
网友
1楼 · 发布于 2024-10-01 16:42:26

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

通信在两个线程中完成,这很糟糕(我将使用异步io)。什么时候 接收到消息时,它调用接收线程中的注册函数,该函数 可能会导致一些线程问题。在

每个通道实例都会创建自己的套接字,但它的可伸缩性要高得多 让通道“主题”由单个实例多路复用。在

一些现有的库提供“通道”功能,如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:

^{pr2}$

过程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

相关问题 更多 >

    热门问题