Java two- way socket connection (server/ client)

一世执手 提交于 2019-12-12 12:00:27

问题


what I'm trying to do is to send some JSON from an Android phone to a Java server, which works fine. The Android/ client side looks like this:

                    Socket s = new Socket("192.168.0.36", 12390);
                s.setSoTimeout(1500);

                JSONObject json = new JSONObject();
                json.put("emergency", false);
                json.put("imei", imei);
                json.put("lat", l.getLatitude());
                json.put("lon", l.getLongitude());
                json.put("acc", l.getAccuracy());
                json.put("time", l.getTime());


                BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
                        s.getOutputStream()));
                out.write(json.toString());
                out.flush();
                s.close();

The server side is this:

        try {
        s = new ServerSocket(port);
    } 
    catch (IOException e) {
        System.out.println("Could not listen on port: " + port);
        System.exit(-1);
    }


    Socket c = null;
    while (true) {
        try {
            c = s.accept();
        } catch (IOException e) {
            System.out.println("Accept failed: " + port);
            System.exit(-1);
        }
        try {

            BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
                String inputLine = null;
            String result = "";
            while ((inputLine = in.readLine()) != null) {
                result = result.concat(inputLine);  
            }
            System.out.println(result);

As I said, all of that works. Now I want to send a message back from the server to the client after it received the message from the client. I extended the code like this, Android/ client side:

                    Socket s = new Socket("192.168.0.36", 12390);
                s.setSoTimeout(1500);

                JSONObject json = new JSONObject();
                json.put("emergency", false);
                json.put("imei", imei);
                json.put("lat", l.getLatitude());
                json.put("lon", l.getLongitude());
                json.put("acc", l.getAccuracy());
                json.put("time", l.getTime());


                BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
                        s.getOutputStream()));
                out.write(json.toString());
                out.flush();

                String inputLine = null;
                String result = "";
                BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));  
                while ((inputLine = in.readLine()) != null) {
                    Log.d(TAG, in.readLine());
                    result = result.concat(inputLine);
                }

And the server side:

        try {
    s = new ServerSocket(port);
} 
catch (IOException e) {
    System.out.println("Could not listen on port: " + port);
    System.exit(-1);
}


Socket c = null;
while (true) {
    try {
        c = s.accept();
    } catch (IOException e) {
        System.out.println("Accept failed: " + port);
        System.exit(-1);
    }
    try {

        BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
            String inputLine = null;
        String result = "";
        while ((inputLine = in.readLine()) != null) {
            result = result.concat(inputLine);  
        }
        System.out.println(result);

    PrintWriter out = new PrintWriter(c.getOutputStream());
    out.write("Hello phone");
    out.flush();
    out.close();

On the client side, nothing ever comes in, it hangs on

                while ((inputLine = in.readLine()) != null) {
                Log.d(TAG, in.readLine());
                result = result.concat(inputLine);
            }

until the socket times out (never enters the loop). I thought it might be a timing problem, for example the server sending out its reply too early and therefore the client never receiving anything, but i tried to put the out.write("Hello phone"); pretty much anywhere in the code, always the same result. Can it have to do with the socket being obtained from ServerSocket and not being able to send out data? What am I missing here, this is bugging me all day ...

Edit: After Nikolais answer, I tried this (client):

                    out.write(json.toString());
                out.newLine();
                out.write("###");
                out.flush();


                String inputLine = null;
                String result = "";
                BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));  
                while ((inputLine = in.readLine()) != null) {
                    if (inputLine.contains("###")) {
                        break;
                    }
                    Log.d(TAG, in.readLine());
                    result = result.concat(inputLine);

                }


                s.close();

and server:

                while ((inputLine = in.readLine()) != null) {

                result = result.concat(inputLine);  
                if (inputLine.contains("###")) {
                    System.out.println("received ###");
                    out.println("Hello phone");
                    out.println("###");
                    out.flush();
                    break;
                }

            }

The idea was to send out the message from the server before the client closes the socket. Still doesnt work ... any hints?


回答1:


On the server side you never get to sending your "Hello phone". Not until client closes the socket, but at that point it's useless. This is because in.readLine() blocks until either data is available or EOF, i.e. socket closed.

You need a way to get out of the reading loop - invent (or adopt) some application-level protocol that would tell you that a whole message is received. Common options are fixed length messages, length prefix, delimited, etc.



来源:https://stackoverflow.com/questions/11653481/java-two-way-socket-connection-server-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!