通过TCP / IP读取数据包时出错

时间:2018-04-19 16:02:22

标签: java byte tcpclient tcp-ip

我正在进行开发,以便通过TCP / IP将一个客户端连接到特定的服务器。我正在创建一个代码,通过TCP / IP发送字节并接收字节。

问题是当我收到数据包时它会中断。

String input;
Traductor traductor = new Traductor();
PrintWriter writer = new PrintWriter(this.socket.getOutputStream(), true);
// Write a message to server       
byte[] theBytesInmediate = new byte[]{0x11, 0x00, 0x14, 0x50, 0x00, 0x01,  0x04, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0x7F, (byte) 0x0A, 0x02, (byte)0x2A, 0x00, 0x02, 0x02, 0x31, 0x00};
DataOutputStream salida = new DataOutputStream(this.socket.getOutputStream());
salida.write(theBytesInmediate);
System.out.println("Packet sent"); 
InputStream input2 = socket.getInputStream();

String tmp ="";
while(true){
     DataInputStream entrada = new 
     DataInputStream(this.socket.getInputStream());
     System.out.println("bytes: " + entrada.readByte());
     try{
        tmp =tmp +  entrada.readUTF();
        System.out.println("readUTF: " + tmp);
     }catch(IOException e){
                System.out.println(e);
     }      
     System.out.println("read: " + entrada.read());
     System.out.println("readChar: " + entrada.readChar());
     System.out.println("readLong: " + entrada.readLong());
}

这是我在控制台中的输出:

enter image description here

一个问题是当我试图获取所有数据包时,如果你在图像上看到它打破了,只能得到一部分。

第二个问题,如果我删除这一行:

System.out.println("read: " + entrada.read());
System.out.println("readChar: " + entrada.readChar());
System.out.println("readLong: " + entrada.readLong());

获取数据包在第一个P空白空白处停止,这是数据包的一部分。

我使用BufferedReader reader = new BufferedReader(new InputStreamReader(input2))进行测试;但是阅读包不正确。

我知道数据包不正确,因为我正在使用Wireshark进行检查。

我需要的数据包的重要部分是告诉13001有mi id。

非常感谢所有人。

更新

感谢EJP的新代码,现在正在工作,但最后还是有一行(我想)。

PrintWriter writer = new PrintWriter(this.socket.getOutputStream(), true);  
byte[] theBytesInmediate = new byte[]{0x11, 0x00, 0x14, 0x50, 0x00, 0x01,  0x04, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0x7F, (byte) 0x0A, 0x02, (byte)0x2A, 0x00, 0x02, 0x02, 0x31, 0x00};
DataOutputStream salida = new DataOutputStream(this.socket.getOutputStream());
String str = new String(theBytesInmediate, StandardCharsets.UTF_8);

writer.println(str);
//writer.flush();
System.out.println("Packet sent"); 
InputStream input2 = this.socket.getInputStream();

BufferedReader reader = new BufferedReader(new InputStreamReader(input2));
String tmp ="";
while(true)
{
   System.out.println("read: " + reader.readLine().toString());
   System.out.println("read: " +reader.read());         
}

输出: enter image description here

如果你在输出中看到错过了最后一个id的ip所在的大paquet。不是一个大问题。但如果我需要结束,那就需要了。

非常感谢所有人。

2 个答案:

答案 0 :(得分:0)

您正在使用readUTF()阅读,但您没有使用writeUTF()撰写文章。看看Javadoc。 readUTF()无法读取使用write()编写的数据。

另一方面,您还需要在ReaderWriter以及输入/输出流之间做出决定。不要混合它们。

答案 1 :(得分:-1)

我将指出一些问题:DataOutputStream要求flush()确定实际写入的输出。您编写的数据似乎与读取方法和结果不一致。在UTF中,P是0x50。 -553882341120是FF FF FF 7F 0A 0A 31 00.正确的方法是write方法与read方法一致,例如readLong应该与writeLong匹配。

相关问题