Sunday 13 December 2020

Android receive messages from socket in python server

I'm trying to get messages from python server after I send messages with this code

I made the code on Android so that every time I click the button, this code will be activated and connected from a new client and the Python will send the message back to all participants who have ever logged in to send to the new client as well

How can I also receive messages from the server?

My code:

class Send extends AsyncTask<String, Void, Void> {
    public Socket socket; // Create socket
    public PrintWriter printWriter; // Create print writer

    protected Void doInBackground(String... strings) {
        String command = strings[0]; // Set the command

        try {
            socket = new Socket("10.0.0.2", 13131); // Set socket connection
            printWriter = new PrintWriter(socket.getOutputStream()); // Set the print writer with socket properties

            printWriter.write(command); // Send the command to server
            printWriter.flush(); // Clear the line
            

            socket.close();
            
        }
        catch (UnknownHostException e) {e.printStackTrace();} // Error exception
        catch (IOException e) {e.printStackTrace();} // Error exception

        return null;
    }
}

I tried with

        InputStream input = socket.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        String line = reader.readLine();

        System.out.println(line);

And I got an error exception:

I/System.out: [socket] e:java.lang.ClassNotFoundException: com.mediatek.cta.CtaUtils

How can I receive the messages?

My python server:

    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Set the socket
    server.bind((socket.gethostname(), 13131)) # Set socket properties

    server.listen()
    (client, (ipNum, portNum)) = server.accept() # Accept to new client

    print("Phone connected")

    while True:
        server.listen()
        (client, (ipNum, portNum)) = server.accept() # Accept to new clients (Accept to new command from the phone)

        Clients.append(client)

        message = str(client.recv(32).decode()) # Set the command as string

        if(message != ""): # Checks if a command has been sent
            print("Client: " + message) # Print the command

            Command(message.lower()) # Process the command

            for Client in Clients:
                Client.send(str(BackMessage).encode())
                Clients.remove(Client)

            print("Server: " + BackMessage) # Print the BackMessage


        else:
            for Client in Clients:
                Client.send(str(BackMessage).encode())
                Clients.remove(Client)

            time.sleep(0.05) # Sleep for 0.05 seconds


from Android receive messages from socket in python server

No comments:

Post a Comment