简体   繁体   中英

Getting a server response via a socket in Java and Android

I'm trying to write an Android client and a Java server.

It works to send a message from the Android client to the server (if the testing code is commented out), but I cannot get the response back from the server to the client.

Could you please help me?

Here's the client:

public class MainActivity extends Activity {

private PrintWriter printwriter;
private EditText textField;
private TextView textView;
private Button button;
private String message;
private String serverResponse;
String fromServer;
Socket clientSocket;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textField = (EditText) findViewById(R.id.editText1);
    textView = (TextView) findViewById(R.id.textView);
    button = (Button) findViewById(R.id.button1);

    final String hostName = "10.111.207.253";
    final int portNumber = 4444;

    button.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            message = textField.getText().toString();
            textField.setText("");

            new Thread(new Runnable() {
                public void run() {
                    try {
                        clientSocket = new Socket(hostName, portNumber);
                        printwriter = new PrintWriter(clientSocket.getOutputStream(),true);
                        printwriter.write(message);

                        // testing only - trying to get the response back from the server
                        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                        while(true) {
                            if ((serverResponse = in.readLine()) != null) {
                                Log.i("server says", serverResponse);
                                break;
                            }
                        }
                        // testing only

                        printwriter.flush();
                        printwriter.close();
                        clientSocket.close();

                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }

            }).start();

            textView.setText("Server: " + serverResponse);
        }
    });
  }
}

And here's the server:

public class MyServer {
    private static ServerSocket serverSocket;
    private static Socket clientSocket;
    private static InputStreamReader inputStreamReader;
    private static BufferedReader bufferedReader;
    private static String message;

    public static void main(String[] args) {
    try {
            serverSocket = new ServerSocket(4444);  
    } catch (IOException e) {
            System.out.println("Could not listen on port: 4444");
    }

    System.out.println("Server started. Listening to the port 4444");

    while (true) {
        try {
            clientSocket = serverSocket.accept();   //accept the client connection
            inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
            bufferedReader = new BufferedReader(inputStreamReader); //get the client message
            message = bufferedReader.readLine();

            if (message != null) {
                System.out.println("Client says: " + message);

                //testing only
                PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
                out.println("response from server");
                //testing only

                inputStreamReader.close();
                clientSocket.close();
            }

        } catch (IOException ex) {
            System.out.println("Problem in message reading");
        }
    }
}

Please help!

You've inserted code to read a reply from the server before you flush your client's PrintWriter . You're not using println() so the boolean you passed to the constructor to enable autoflush doesn't apply as stated in the javadoc :

Unlike the PrintStream class, if automatic flushing is enabled it will be done only when one of the println, printf, or format methods is invoked, rather than whenever a newline character happens to be output. These methods use the platform's own notion of line separator rather than the newline character.

This means the client is never sending anything, therefore the server never receives anything. Back in the client you'll block forever waiting for a reply that is never coming.

Either use printwriter.println() to send your message, or move printwriter.flush() to before you attempt to read a reply from the server.

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