解析来自Android套接字的Python套接字中的JSON

时间:2019-06-04 14:15:36

标签: android python json sockets

我有一个正在发送JSON数据的Android套接字客户端。在后端,我有一个正在侦听的python套接字服务器。我在解析数据时遇到了麻烦。这是我到目前为止的内容:

Android客户端:

public class SendMessage extends AsyncTask<String, Void, Void> {

    private static final String server_ip = "192.168.2.151";
    private static final int server_port = 5490;

    @Override
    protected Void doInBackground(String... params) {
        try{
            try{
                Socket socket = new Socket(server_ip, server_port);

                DataOutputStream out = new                                                 
                                DataOutputStream(socket.getOutputStream());

                JSONObject obj = new JSONObject();
                obj.put("message", "Delivery Request");

                out.writeBytes(obj.toString());
                out.flush();
                out.close();

            } catch (IOException e){
                e.printStackTrace();
                Log.d(TAG, "IOException: " + e.toString());
            }

        } catch (Exception e){
            this.exception = e;
            Log.d(TAG, "Exception: " + e.toString());
            return null;
        }
        return null;
    }
}

Python服务器:

class Server():
    def __init__(self, host, port):
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.conn = self.socket
        self._host = host
        self._port = port

        self.timeout = 2.0
        self._bind()

    def _bind(self):
        self.socket.bind( (self._host, self._port) )        

    def accept_connection(self):
        self.socket.listen(1)
        self.conn, addr = self.socket.accept()
        self.conn.settimeout(self.timeout)

    def read_obj(self):
        msg = self.conn.recv(1024)
        msg = msg.decode('utf-8')
        msg = json.loads(msg)
        """ ERROR HERE """

    def start(self):
        while True:
            self.accept_connection()
            self.read_obj()

最初,当我做msg = self.conn.recv(1024)时,我得到了字节:b'{"message":"Delivery Request"}'

然后我尝试使用utf-8:msg = msg.decode('utf-8')对其进行解码,然后返回一个字符串:{"message":"Delivery Request"}

但是奇怪的是,当我print(msg)时,没有引号

最后,我尝试获取一些JSON:msg = json.loads(msg),并且收到此错误:json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

0 个答案:

没有答案