繁体   English   中英

Java中的套接字编程以发送和接收字节数组

[英]Socket Programming in Java to send and receive byte array

是Android的新手,我在套接字编程方面遇到了问题。

class ClientAsycTask extends AsyncTask<String,Void,String>{
    ProgressDialog progress;
    @Override
    protected void onPreExecute() {
        progress = new ProgressDialog(MainActivity.this);
        progress.setMessage("Connection Server Please wait");
        progress.setIndeterminate(true);
        progress.show();
    }

    @Override
    protected String doInBackground(String... params) {
        String result = null;
        Socket socket = new Socket();
        String host = "systemteq.gotdns.com";
        Integer port = 4999;
        DataOutputStream s_out = null;
        BufferedReader s_in = null;
        try{
            socket.connect(new InetSocketAddress(host, port));
            s_out = new DataOutputStream( socket.getOutputStream());
            s_in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            byte[] messages = new byte[]{0x10,0x01,0x03,0x00,0x00};
            s_out.write(messages);
            String response;
            while((response = s_in.readLine())!=null){
                result += response;
            }
            //result = "Successfully"+s_in.read();//s_in.readLine();
            socket.close();

        }catch (Exception e){
            Toast.makeText(MainActivity.this,"systemteq.gotdns.com:4999 not connected",Toast.LENGTH_SHORT).show();
        }
        return result;
    }

    @Override
    protected void onPostExecute(String s) {
        if(progress.isShowing()){
            progress.dismiss();
        }
        Toast.makeText(MainActivity.this,"Connected "+s,Toast.LENGTH_SHORT).show();
        tv.setText(s);
    }
}

上面的代码向服务器发送一个十六进制代码,服务器以一些十六进制代码作为响应,例如10 01 20 10 00. [五个字节]。

但是,当我在代码进度上方运行时,对话框永远不会关闭。 解决后,我发现s_in.readLine()在读取服务器响应时存在一些问题。

我已经通过很多链接,但是在解决此问题时并没有成功。 请帮助我解决这个问题。

更新:-

使用DataInputStream之后:

s_in = new DataInputStream(socket.getInputStream());
            byte[] messages = new byte[]{0x10,0x01,0x03,0x00,0x00};
            s_out.write(messages);
            String response;
            System.out.println("START");
            result = s_in.readUTF();

它仍然不占用响应字节。 虽然请求成功。

更新2

byte m = s_in.readByte();
result = Byte.toString(m);

现在正在获取字节值,但我应该获取5个字节,而不是获取5个字节而仅获取一个。 请帮我做这件事

如果您在等待二进制数据,请不要使用InputStreamReader ,而应尝试使用DataInputStream
readLine()等待'\\ n','\\ r',“ \\ r \\ n”或阅读器的结尾。

更新:如果您知道确切的字节数,则将它们读入数组。

byte[] buf = new byte[5];
s_in.read(buf);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM