从Python套接字服务器到Java套接字客户端接收字符串

时间:2019-02-23 14:10:21

标签: java android python sockets serversocket

我正在制作一个Android应用程序(使用后台服务),该应用程序从Python Server接收字符串,问题是Android服务仅在通信中断时才接收字符串。

Java代码

public class Receiver implements Runnable {

    private Client client;
    private Socket socket;
    private Thread receiver;
    private BufferedReader br;

    public Receiver(Socket socket, Client client) {
        this.socket =socket;
        this.client = client;
    }

    @Override
    public void run() {
        receiver = Thread.currentThread();
        try {
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            while(!receiver.isInterrupted()){
                String command = br.readLine();
                System.out.println("Command Received: "+command);
                client.parseCommand(command);
            }
        } catch (Exception e) {
            receiver.interrupt();
            try {
                br.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            new Thread(new ConnectionController()).start();
        }

    }
}

我也尝试过使用DataInputStream,但是如果我使用它,Android服务将永远不会接收到字符串。

Python代码

def send_command(self,command):
        self.currentClient[1].send(command.encode())

我使用这种方法发送命令字符串。

0 个答案:

没有答案