首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Buffered Reader获取不同的字节

使用Buffered Reader获取不同的字节
EN

Stack Overflow用户
提问于 2014-03-29 18:12:40
回答 1查看 67关注 0票数 0

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

代码语言:javascript
复制
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) {
        }
    }
}
EN

回答 1

Stack Overflow用户

发布于 2014-03-29 19:11:39

读取器将收到的字节转换为字符,并使用系统属性file.encoding (您可以对其进行更改)。

如果你需要字符(字符串),你必须用一种已知的编码(如UTF-8)以字节为单位进行解码和编码。它在客户端和服务器上应该(必须)相同。

如果你只需要字节(不需要字符,不需要字符串),你应该只使用流--不需要读取器

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22729692

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档