无法将JSON数据发送到服务器(不允许发送或接收数据的请求)Android到Python

时间:2016-08-30 11:08:46

标签: python python-3.x

我想从Android客户端向Python服务器发送一个Json对象,并将响应文本发送回客户端。但它显示错误

  

不允许发送或接收数据的请求

服务器

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))
        print("Listening.....")

    def listenS(self):
        self.sock.listen(5)
        while True:
            client, address = self.sock.accept()
            print("Accepted from  :: "+str(address))

            threading.Thread(target = self.listenToClientS,args = (client,address)).start()

    def listenToClientS(self, client, address):

            data = self.sock.recv(1024)
            Mydata = json.load(data)
            print(Mydata)                

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

客户端

public class client {

    private String serverIpAddress = "IP";
    private boolean connected = false;
    private int serverPort = 5000;    

    protected void connect() {

        if (!connected) {
            if (!serverIpAddress.equals("")) {
                Thread cThread = new Thread(new ClientThread());
                cThread.start();
            }
        }
    }
public class ClientThread implements Runnable {

    public void run() {
        try {
            InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
            Log.d("ClientActivity", "C: Connecting...");
            Socket socket = new Socket(serverIpAddress,serverPort);
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            JSONObject json = new JSONObject();
            json.put("myData", 23);
            String myJsonObjectSerialized = json.toString();
            oos.writeObject(myJsonObjectSerialized);
            oos.flush();
            oos.close();

            socket.close();
            Log.d("ClientActivity", "C: Closed.");
        } catch (Exception e) {
            Log.e("ClientActivity", "C: Error", e);
            connected = false;
        }
    }
}

0 个答案:

没有答案