用Java编写Socket发送和接收字节数组

用Java编写Socket发送和接收字节数组,java,android,sockets,tcpclient,Java,Android,Sockets,Tcpclient,我是android新手,我对socket编程有问题 class ClientAsycTask extends AsyncTask<String,Void,String>{ ProgressDialog progress; @Override protected void onPreExecute() { progress = new ProgressDialog(MainActivity.this); progress.setM

我是android新手,我对socket编程有问题

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);
    }
}
它仍然不接受响应字节。虽然请求成功

更新2

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

现在我得到字节值,但我应该得到5个字节,而不是5个字节,我只得到一个。请帮我解决这个问题

如果您正在等待二进制数据,请不要使用
InputStreamReader
,而是尝试
DataInputStream

readLine()

更新:若您知道确切的字节数,请将它们读入数组

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

如果您正在等待二进制数据,请不要使用
InputStreamReader
,而是尝试使用
DataInputStream

readLine()

更新:若您知道确切的字节数,请将它们读入数组

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

如果服务器向您发送字节,为什么您总是尝试将它们作为字符串读取?读取字节到字节[]缓冲区。这很容易。字符串更复杂。Hai@Eugene Krivenja谢谢,这现在可以很好地工作,但现在一次只占用一个字节。据我所知,它将返回5个字节。有吗idea@RKD不,
readUTF()
readLine()
做的事情不同,最粗略地看一下文档就会发现。hi@EJP thanx,实际上我使用readByte时的响应是24,当我将其转换为十六进制时,它是18,这是响应的第一个字节。答复是18060500。你能不能告诉我,如果服务器发送字节给你,你为什么总是把它们读成字符串?读取字节到字节[]缓冲区。这很容易。字符串更复杂。Hai@Eugene Krivenja谢谢,这现在可以很好地工作,但现在一次只占用一个字节。据我所知,它将返回5个字节。有吗idea@RKD不,
readUTF()
readLine()
做的事情不同,最粗略地看一下文档就会发现。hi@EJP thanx,实际上我使用readByte时的响应是24,当我将其转换为十六进制时,它是18,这是响应的第一个字节。答复是18060500。你能告诉我怎么才能把这些字节都拿走吗