简体   繁体   English

服务器未正确读取发送的UDP数据包

[英]UDP Packet sent not being read by server correctly

I'm sending two packets from a client to server. 我正在从客户端向服务器发送两个数据包。 The issue I'm having is the data being read on the server makes both strings the same length with regards to the longest string sent. 我遇到的问题是,在服务器上读取的数据使两个字符串的长度相同(关于发送的最长字符串)。 For example: 例如:

if string 1 was : 1234 如果字符串1为: 1234
and string 2 was: abcdefghi 字符串2是: abcdefghi

the server would read 服务器将读取

1234efghi
abcdefghi

It should just display 它应该只显示

1234
abcdefghi

My code is: 我的代码是:

byte[] toSendUser = new byte[1024];
byte[] toSendPass = new byte[1024];

String name = "1234";
String password = "abcdefghi"; 

    toSendUser = name.getBytes();
        toSendPass = password.getBytes();
        DatagramPacket packSend = new DatagramPacket (toSendUser, toSendUser.length, ipConn, 9876); 
        connection.send(packSend);

        DatagramPacket packSendtwo = new DatagramPacket (toSendPass, toSendPass.length, ipConn, 9876); 
        connection.send(packSendtwo);

Could it be a server issue or is my code wrong in my client? 可能是服务器问题,还是我的客户端代码错误?

DatagramPackets in Java keep shrinking to the size of the smallest one received so far. Java中的DatagramPackets一直缩小到目前为止接收到的最小DatagramPackets的大小。 You have to either create a new one per receive(), or at least reset the length every time before the next receive(). 您必须为每个receive(),创建一个新的receive(),或者至少每次下一个receive().之前都要重新设置长度receive().

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM