我试图编写一个asyncore服务器来处理手机和芯片。
我尝试通过识别它们发送的消息字符串来确定哪个连接适用于芯片或电话。如果芯片说"帮助,太多水",服务器发送消息"太多的水"打电话。
class RequestHandler(asyncore.dispatcher):
def __init__(self, sock, q, addr):
self.sock = sock
self.q = q
def handle_read(self, sock):
self.q = q
c = self.sock.recv(1024).rstrip('\n')
c2 = c.rstrip()
comment = c2.split(',')
if comment[2] == "chip": # To identify chip or phone
self.chip = self.sock
print("chip is "+str(tuple(addr)))
if commentTable[comment[0]] == 7:
self.comment = 7
self.q.put(msgTable[int(comment[1])])
else:
self.comment = commentTable[comment[0]]
else:
self.android = self.sock
print("android is"+str(tuple(addr)))
def handle_write(self):
if self.q.empty():
if self.comment == 0:
self.android.send("time,"+"pH,"+"waterlevel,"+"light"+"video")
else:
while not self.q.empty():
self.sock.send(self.q.get())
程序的结果是服务器不会将消息发送给任何人。
服务器:
Binding on port = 5000
Connect with('192.168.0.121', 47082)
Connect with('192.168.0.121', 47084)
.....
电话:
$ ./client 192.168.0.121 5000
Please enter the message: state,
它没有打印手机或芯片的信息。
抱歉,我忘了粘贴关于服务器类的代码。
class server_socket(asyncore.dispatcher):
def __init__(self, host, port):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind((host, port))
self.listen(5)
print("Binding on port = 5000")
def handle_accept(self):
pair = self.accept()
if pair is not None:
sock, addr = pair
print("Connect with" + str(tuple(addr)))
handler = RequestHandler(sock, queue, addr)