我已经开始使用 Python 好几次了,现在,我正在创建一个套接字服务器。我已经让服务器在多个客户端的多个线程上运行(万岁!)但我正在寻找我无法调用的功能(我什至不知道它是否存在)我想创建一种 channel ,其中客户端可以发送不同类型的消息。
我创建一个 channel 信息的例子,如果服务器收到这种类型的套接字,它就打印
我创建了另一个 channel 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 实例接收消息(例如在单独的进程中)。
通信是在两个线程中完成的,这很糟糕(我会使用异步 io)。什么时候 接收到一条消息,它调用注册函数在接收线程中 可能会导致一些线程问题。
每个 Channel 实例都创建自己的套接字,但它的可扩展性要高得多 让 channel “主题”由单个实例复用。
一些现有的库提供“ 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
关于python - 如何在 Python 中使用套接字创建 channel ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25058578/