【问题标题】:UDP java not sending full stringUDP java没有发送完整的字符串
【发布时间】:2018-09-06 13:47:33
【问题描述】:

我正在使用 java 和 UDP 做一个简单的投票系统。我这里有三台电脑,一台是服务器,一台添加候选人,一台用于投票。发送候选人并将它们添加到服务器工作正常,但每当我必须将候选人数据发送到第三台计算机时,我的字符串永远不会完全收到。每个候选人都存储在一个对象中,我在其中存储每个候选人的 name[String] 和 votes[int],所有这些都存储在一个数组列表中。

InetAddress IPres = InetAddress.getByName(IPresimp);
String name = candidate.get(pos).name;
String posi = Integer.toString(pos);
String candidate = name.concat(":" +posi);
set = new DatagramPacket(candidate.getBytes(), 0, candidaate.getBytes().length, IPres, get.getPort());
socket.send(set);

我是这样发送的,所以每当我将候选人的姓名发送到第三台计算机时,我也会发送我当前正在评估的职位,例如,我应该发送类似“Obama:2”的内容。但是每当我收到包裹时,我只会得到“奥巴马”,我添加到字符串中的任何内容都不会发送。

接收代码:

try {
    byte[] buffer = new byte[400];
    get = new DatagramPacket(buffer, buffer.length);
    socket.receive(get);
    String info = new String(get.getData());
    System.out.println(info);
}
catch (IOException ex) {
    Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
} 

【问题讨论】:

  • 此数据太短,无法按照您在发送中的描述截断。问题出在接收代码中。
  • 什么意思?这是我接收数据的方式try { byte[] buffer = new byte[400]; get = new DatagramPacket(buffer, buffer.length); socket.receive(get); String info = new String(get.getData()); System.out.println(info); } catch (IOException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); }
  • 这可能是俄罗斯黑客试图操纵你的选举:-)
  • 你是什么意思我是什么意思? '问题在于接收代码'的哪一部分你不明白?

标签: java udp send


【解决方案1】:
String info = new String(get.getData());

问题出在接收代码中。应该是:

    String info = new String(get.getData(), get.getOffset(), get.getLength());

目前你忽略了DatagramPacket的实际长度,假设它填满了缓冲区,而String填满了垃圾。

【讨论】:

    猜你喜欢
    • 2014-10-15
    • 2018-03-28
    • 2017-04-20
    • 1970-01-01
    • 1970-01-01
    • 2017-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多