发送命令后,建立套接字连接等待响应

时间:2014-07-04 08:47:28

标签: java android sockets

从android应用程序,我正在使用android服务创建套接字连接。我的想法是,当活动开始时,我正在连接到服务器,并且我正在打开套接字连接,以便我可以访问应用程序的其他部分。

现在我想要做的就是我正在使用缓冲编写器向服务器写命令。写入后我想实现检查是否已经收到响应。我正在尝试使用while (inStream.available() == 0)循环执行此操作。但这不起作用。任何想法如何使应用程序等待特定命令的响应,直到处理更多代码?

连接到插座:

    public class connectSocket implements Runnable
{
    @Override
    public void run()
    {
        try
        {
            Log.v("DEV","SocketClass, connectSocket");
            SocketAddress socketAddress = new InetSocketAddress(SERVERIP,SERVERPORT);
            command = "authorization";

            try
            {
                socket = new Socket();
                socket.setTcpNoDelay(true);
                socket.setSoTimeout(5000);
                socket.connect(socketAddress, 5000);

                if (socket.isConnected())
                {
                    Log.v("DEV","SocketClass successfully connected!");

                    out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    inStream = new DataInputStream(socket.getInputStream());

                    int bytesRead;
                    int count = 1;

                    while ((bytesRead = in.read()) > 0 && count != 3)
                    {
                        if (count == 1)
                        {
                            out.write(command + "\r\n");
                            out.flush();
                        }

                        while (inStream.available() == 0)
                        {
                            Log.v("DEV", "sleep "+inStream.available());
                            android.os.SystemClock.sleep(100);
                        }

                        StringTokenizer filterToken = new StringTokenizer(in.readLine(), "^");
                        String temp = filterToken.nextToken();

                        Log.v("DEV", "SocketClass Tokenizer: "+temp);

                        if (temp.equals("cmd_main"))
                        {
                            response = filterToken.nextToken();

                            Intent ret = new Intent();
                            ret.setAction(Testas.RECEIVE_AUTHORIZATION);
                            ret.putExtra("response",response);
                            sendBroadcast(ret);
                            count = 2;
                        }

                        count++;
                    }
                }
            }

            catch (Exception e)
            {
                Log.e("TCP",e.toString());
            }
        }

        catch (Exception e)
        {
            Log.e("DEV",e.toString());
        }
    }
}

我想等待回复:

    class trackerStatus implements Runnable
{
    @Override
    public void run()
    {
        Log.v("DEV", "Socket Class, trackerStatus");

        try
        {
            int bytesRead;
            boolean parse = true;
            command = "command";
            int count = 1;

            while ((bytesRead = in.read()) > 0 && parse)
            {
                if (count == 1)
                {
                    out.write(command + "\r\n");
                    out.flush();
                }

                while (inStream.available() == 0)
                {
                    ////this part is not working
                    Log.v("DEV", "sleep "+inStream.available());
                    android.os.SystemClock.sleep(100);
                }
                Log.v("DEV", "NoSleep "+inStream.available());
                response = in.readLine();

                Log.v("DEV","ReadLine: "+response);

                if (response == null || "".equals(response.trim()))
                {
                    Log.v("DEV","Test Empty");

                    Intent ret = new Intent(Testas.RECEIVE_TRACKER_STATUS);
                    ret.putExtra("status", "OFFLINE");
                    LocalBroadcastManager.getInstance(SocketService.this).sendBroadcast(ret);

                    parse = false;
                }

                else
                {
                    StringTokenizer filterToken = new StringTokenizer(response, "^");
                    String temp = filterToken.nextToken();

                    if (temp.equals("trackerinfo"))
                    {
                        StringTokenizer extraFilter = new StringTokenizer(response, "|");
                        temp = extraFilter.nextToken();
                        String[] separate = temp.split(":");

                        if (separate[1].equals(carId))
                        {
                            Intent ret = new Intent();
                            ret.setAction(Testas.RECEIVE_TRACKER_STATUS);
                            ret.putExtra("status", "ONLINE");
                            sendBroadcast(ret);
                            parse = false;
                        }

                    }
                }

                count++;
            }
        }

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

1 个答案:

答案 0 :(得分:3)

            while (inStream.available() == 0)
            {
                ////this part is not working
                Log.v("DEV", "sleep "+inStream.available());
                android.os.SystemClock.sleep(100);
            }
            Log.v("DEV", "NoSleep "+inStream.available());

删除所有内容。

            response = in.readLine();

保持这一点。它将阻塞,直到数据可用或检测到流结束。