如何在不发送数据的情况下在Android中监听DataInputStream Socket?

时间:2018-08-15 05:08:47

标签: android sockets datainputstream

我写了一个可以通过套接字发送和接收数据的类。问题是如何在不发送数据的情况下接收数据(侦听套接字)?在此类中,首先,我使用特定的端口和IP连接到套接字,然后初始化outputstrem和inputstram。我可以轻松地发送和接收数据,但是只有在我这边有请求时,我才能接收数据。有时我必须在不发送数据的情况下接收新信息。有可能吗?

这是我的代码:有人可以指导我如何立即收听套接字inputstrem吗?谢谢你。

public class INetConnection{

    private DataOutputStream       outputStream;
    private DataInputStream inputStream;
    private Callback mCallback;
    private Socket socket;
    private byte[] rec_buffer;

    public Socket getSocket() {
        return socket;
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }

    /**
     *
     */
    public void connectToNetwork() {
        if (socketConnect()) {
            try {
                outputStream = new DataOutputStream(getSocket()
                        .getOutputStream());
                inputStream = new DataInputStream(getSocket().getInputStream());
                Log.i("Log", "Streams Created!");
                receiveData();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     *
     */
    private boolean socketConnect() {
        try {
            socket = new Socket(SERVER_IP, SERVER_PORT);
            Log.i("Socket", "Connection stablished");
            return true;
        } catch (UnknownHostException e) {
            Log.d("Exception mode", "UnknownHostException");
            e.printStackTrace();
        } catch (IOException e) {
            Log.d("Exception mode", "IOException");
            e.printStackTrace();
        }
        return false;
    }

    /**
     *
     */
    public void sendData(final byte[] data) {
        outputStream.write(data, 0, data.length);
    }

    /**
     *
     */
    private void receiveData(){
        // Again, probably better to store these objects references in the support class
        if(getSocket() != null && getSocket().isConnected()){
            try {
                Log.i("Log", "Ready to receive!");
                byte[] buffer  = new byte[265536];
                int size = 0;
                while ((size = inputStream.read(buffer)) != -1){
                    Log.i("Log", "Data's been read fully from server");
                    rec_buffer  = new byte[size];
                    rec_buffer = Arrays.copyOfRange(buffer, 0 , size);
                    for (int i = 0; i< size; i++)
                        Log.i("Log", "Data i: " + rec_buffer[i]);
                }
            } catch (IOException e) {
                Log.e("Log", "Error occured during receiving data");
                e.printStackTrace();
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您要通过套接字连接的服务器是您自己的具有自己实现的服务器还是别人的服务器?

通常,服务器的行为方式是仅根据请求发送数据(至少REST API行为如此)。但是,如果这是您自己的服务器,则可以通过以下方式进行设置:连接套接字后,它将开始向客户端发送数据。这样,您客户端上的InputStream应该能够在不发送任何内容的情况下接收数据。

如果不是您要修改的服务器,并且希望客户端首先发送请求,那么我想除了首先从客户端发送数据外,您无能为力。