在java中通过套接字流接收错误的字节值

发布于 2024-12-10 06:30:12 字数 276 浏览 0 评论 0原文

我尝试将文件作为字节数组读取并通过套接字连接通过网络发送, 我在从文件读取后(在发送之前)打印了字节的值,并在从套接字接收到它后打印了字节的值......这是不同的!它收到的值是错误的我不知道为什么

在发送之前采样字节: 21、 0, 52、 0 接收后的样本字节: -8, -1, -4, -1

我使用 write(byte[] b) 发送字节; OutputStream 类 并使用 read(byte[] b, int off, int len); 接收字节输入流类。

谁能帮助我吗?

I try to read a file as a byte array and send it through network over socket connection,
I printed the values of the bytes after reading from file(before sending it) and printed the values of bytes after receiving it from socket ... and it was different! it is received in wrong values I don't know why

sample bytes before sending:
21,
0,
52,
0
sample bytes after receiving:
-8,
-1,
-4,
-1

I sent the bytes using write(byte[] b); of OutputStream class
and received bytes using read(byte[] b, int off, int len); of InputStream class.

can anyone help me?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冰魂雪魄 2024-12-17 06:30:12

你可以尝试

ServerSocket ss = new ServerSocket(0);
Socket c = new Socket("localhost", ss.getLocalPort());

byte[] bytes = {21, 0, 52, 0};
c.getOutputStream().write(bytes);
c.close();

byte[] bytes2 = new byte[4];
Socket s = ss.accept();
ss.close();

new DataInputStream(s.getInputStream()).readFully(bytes2);
System.out.println(Arrays.toString(bytes2));
s.close();

打印

[21, 0, 52, 0]

You can try

ServerSocket ss = new ServerSocket(0);
Socket c = new Socket("localhost", ss.getLocalPort());

byte[] bytes = {21, 0, 52, 0};
c.getOutputStream().write(bytes);
c.close();

byte[] bytes2 = new byte[4];
Socket s = ss.accept();
ss.close();

new DataInputStream(s.getInputStream()).readFully(bytes2);
System.out.println(Arrays.toString(bytes2));
s.close();

prints

[21, 0, 52, 0]
执手闯天涯 2024-12-17 06:30:12

请小心将字节和字符视为可互换的。字节已签名!

Be careful treating bytes and chars as interchangeable. Bytes are signed!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文