This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center
                            
                        
                    
                
                已关闭8年。
            
        

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

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

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

谁能帮我?

最佳答案

你可以试试

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]

关于java - 通过java中的套接字流接收到错误的字节值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7797298/

10-13 05:30
查看更多