以客户端的身份侦听特定端口号上的套接字

时间:2018-08-27 12:53:37

标签: android sockets client inputstream

例如,我想知道在应用程序为客户端时如何监听特定端口; IP:127.0.0.1和端口号12345。有一个Windows应用程序,可以每2分钟监听一次来自服务器的传入数据,但是Inputstrem根本不起作用。它仅在我将请求代码发送到服务器时才起作用。我怎么解决这个问题?预先感谢

这是我的接收方代码:

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[8192];
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int bytesRead = -1;
            while((bytesRead = inputStream.read(buffer)) != -1){
                baos.write(buffer, 0, bytesRead );
                rec_buffer = baos.toByteArray();
                for (int i = 0; i< size; i++)
                    //Log.i("Log", "Data i: " + rec_buffer[i]);
                    Log.i("Log", "Data i: " + String.format("0x%20x", rec_buffer[i]));
                mResponseHandler.post(new Runnable(){
                    @Override
                    public void run(){
                        if(mCallback != null){
                            baos.reset();
                            mCallback.onDataReceived(rec_buffer);
                        }
                    }
                });
            }

        } catch (IOException e) {
            Log.e("Log", "Error occured during receiving data");
            e.printStackTrace();
        }
    }
}

0 个答案:

没有答案