下面的代码是UDP接收数据的一部分
- class UDPReceive implements Runnable{
- public DatagramSocket ds = null;
- public void run(){
- try {
- ds = new DatagramSocket(10002);
- } catch (SocketException e) {
- System.out.println("绑定端口失败");
- }
- String buf = null;
- while(true){
- try {
- byte[] data = new byte[1024];
- DatagramPacket dp = new DatagramPacket(data, data.length);
- ds.receive(dp);
- buf = new String(data);
- System.out.println(buf+" : "+buf.length()); //奇怪的是这里
- } catch (Exception e1) {
- e1.printStackTrace();
- }
- }
- }
- }
复制代码 假如发送端发的数据是:这是个很奇怪的数据
这段数据字符串长度为9
打印的结果却是:
这是个很奇怪的数据 : 1015 数据是没有错,但是打印的长度却不是9,是定义的接收数据的byte数组长度减去9,为1015 为什么会这样
|