使用Buffered Reader获取不同的字节

时间:2014-03-29 10:12:40

标签: java sockets

当我将一些字节放入客户端套接字OutputStream并将它们传递给服务器套接字时,我遇到了问题。使用BufferedReader我想读取那些字节,但方法read()获取字符,所以我在范围<-128,-1>...中发送字节时通常会得到不同的值。我怎样才能将这些字符转换为我想要的字节。

public class Client {

    public static void main(String[] args) {
        Socket s = null;
        InputStream is = null;
        OutputStream os = null;
        try {
            s = new Socket("localhost", 3000);
            is = s.getInputStream();
            os = s.getOutputStream();
            int read;
            String str = "";
            while ((read = is.read()) != '\n') {
                str += (char) read;
            }
            System.out.println(str);
            ByteBuffer b = ByteBuffer.allocate(4);
            b.order(ByteOrder.BIG_ENDIAN);
            b.putInt(430);
            byte[] message = b.array();
            for (int i = 0; i < message.length; i++) {
                System.out.println(message[i] + " ");
            }
            os.write(message);
        } catch (Exception ex) {
        }
    }
}



class Robot extends Thread {

    private Socket s;

    public static void main(String[] args) {
        ServerSocket ss = null;
        try {
            ss = new ServerSocket(3000);
            while (true) {
                Socket s = ss.accept();
                Robot srv = new Robot();
                srv.s = s;
                srv.start();
            }

        } catch (NumberFormatException numberEx) {
            System.out.println("Port of port is not integer");
        } catch (IOException ioEx) {
            System.out.println("Input connection problem");
        } finally {
            try {
                ss.close();
            } catch (IOException ex) {
                ex.printStackTrace();
                Logger.getLogger(Robot.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    @Override
    public void run() {
        BufferedReader is = null;
        OutputStream os = null;
        try {
            is = new BufferedReader(new InputStreamReader(s.getInputStream()));
            os = s.getOutputStream();
            os.write("Send me data:\n".getBytes());
            int b;
            while ((b = is.read()) != -1) {
                System.out.println((byte) b + " ");
            }
        } catch (Exception ex) {
        }
    }
}

1 个答案:

答案 0 :(得分:0)

Reader会转换收到的字符数并使用系统属性file.encoding(您可以更改它)。

如果需要字符(字符串),则必须使用已知编码(例如UTF-8)对字节进行解码和编码。它应该(必须)在客户端和服务器上相同。

如果你只需要字节(没有字符,没有字符串)你应该只使用Streams - 没有读者