简体   繁体   中英

Send data from Android mobile to java server

I try to send data from my Android mobile to a java server. I done the server application and simulated a client directly from it by starting a "ClientConnexion" thread. It works fine, the data is coming and I can read it.

Then, I copy ma "ClientConnexion" class to my Android mobile, as it.

When debuging on my server, I see that connection is correctly established, but reading function is blocking, as if data was never incoming. However, debugging on Android side shows that it (seems) sent.

Here is my ClientConnexion code:

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Random;

public class Client implements Runnable{

    private Socket connexion = null;
    private PrintWriter writer = null;
    private BufferedInputStream reader = null;

    public Client(String host, int port){
        try {
            connexion = new Socket(host, port);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void run(){

        try {

            writer = new PrintWriter(connexion.getOutputStream(), true);
            reader = new BufferedInputStream(connexion.getInputStream());

            // COMMAND is received by server when emulating client directly from it
            // COMMAND is NOT received when sent from Android mobile
            writer.write("COMMAND");
            writer.flush();

            System.out.println("COMMAND sent");

            String response = read();
            System.out.println("Response : " + response);

            } 
        catch (IOException e1) {
            e1.printStackTrace();
        }

    writer.write("CLOSE");
    writer.flush();
    writer.close();

    }

    private String read() throws IOException{
        String response = "";
        int stream;
        byte[] b = new byte[4096];
        stream = reader.read(b);
        response = new String(b, 0, stream);
        return response;
    }
}

What could be blocking on the Android client side ? No exception is thrown.

make sure your connection is working properly,maybe your android client and your server in different network segment? Last you can debug or log you client.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM