简体   繁体   English

通过Java和Android中的套接字获取服务器响应

[英]Getting a server response via a socket in Java and Android

I'm trying to write an Android client and a Java server. 我正在尝试编写Android客户端和Java服务器。

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. 它可以将消息从Android客户端发送到服务器(如果测试代码被注释掉),但是我无法从服务器将响应返回到客户端。

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 . 刷新客户端的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 : 您没有使用println()所以传递给构造函数以启用自动刷新的布尔值不适用于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. 与PrintStream类不同,如果启用了自动刷新,则仅在调用println,printf或format方法之一时才执行此操作,而不是在输出换行符时才执行。 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. 在尝试从服务器读取答复之前,请使用printwriter.println()发送消息,或者将printwriter.flush()移至。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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