Java双向套接字连接(服务器/客户端) [英] Java two- way socket connection (server/ client)

查看:106
本文介绍了Java双向套接字连接(服务器/客户端)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是从Android手机向Java服务器发送一些JSON,效果很好. Android/客户端如下所示:

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();

服务器端是这样:

        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);

正如我所说,所有这些都有效.现在,我想在收到来自客户端的消息后,将消息从服​​务器发送回客户端. 我在Android/客户端扩展了这样的代码:

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);
                }

和服务器端:

        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);
            }

直到套接字超时(从不进入循环).我认为这可能是时间问题,例如服务器过早发出答复,因此客户端从未收到任何东西,但是我试图将out.write("Hello phone");放回去.几乎在代码中的任何地方,总是相同的结果.它可以与从ServerSocket获得的套接字有关,而不能发送数据吗?我在这里想念的是什么,这整天困扰着我……

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 ...

尼古拉斯回答之后,我尝试了此操作(客户端):

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();

和服务器:

                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?

推荐答案

在服务器端,您永远不必发送"Hello电话".直到客户端关闭套接字,这才没有用.这是因为in.readLine()会阻塞,直到有数据可用或EOF为止,即套接字已关闭.

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.

这篇关于Java双向套接字连接(服务器/客户端)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆