Python检查UDP消息

时间:2016-11-21 16:58:58

标签: python python-3.x udp

这是我的客户:

import socket
import threading

class ThreadedServer(object):
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.bind((self.host, self.port))

    def listen(self):
        self.sock.listen(5)
        while True:
            client, address = self.sock.accept()
            client.settimeout(60)
            threading.Thread(target = self.listenToClient,args = (client,address)).start()

    def listenToClient(self, client, address):
        size = 1024
        while True:
            try:
                data = client.recv(size)
                if data:
                    # Set the response to echo back the recieved data 
                    response = data
                    client.send(response)
                else:
                    raise error('Client disconnected')
            except:
                client.close()
                return False

if __name__ == "__main__":
    ThreadedServer('',5000).listen()

我正在尝试解析收到的消息。我尝试过以下方法: 如果数据:

            if data == "command":
                print("Command Received")
            elif data != "command":
                response = data
                client.send(response)
        else:
            raise error('Client disconnected')

我已将数据打印到控制台,它以b'command'形式出现,我尝试在等于字符串中使用它,当我从我的客户端发送它时,它仍然不打印'Command receieved'到服务器并发送消息执行以下mySocket.send(message.encode())我想知道如何解决我的问题?

1 个答案:

答案 0 :(得分:0)

刚刚找到解决方案:打印时必须解码UDP消息。

示例:

print data.decode()