本帖最后由 NewDemo 于 2014-4-17 18:02 编辑
在做UDP接收端的时候,为什么最后一句话没有打印出来很多0呢?难道这个getData()方法对字节数组的内容进行了有效判断吗?以下是代码
- import java.net.*;
- class Test3
- {
- public static void main(String[] args) throws Exception
- {
- method_0();
- }
- //接收端 1.创建socket服务 2.定义数组,包,存储接收到的数据 3.使用dp中的方法 4.关闭资源
- public static void method_0()throws Exception{
- DatagramSocket ds = new DatagramSocket(10009);
- while(true){
- byte[] buf = new byte[1024];
- DatagramPacket dp = new DatagramPacket(buf,buf.length);
- ds.receive(dp);
- for(byte b:buf){
- System.out.print(b);//此时打印的将是很多0。
- }
- System.out.println(new String(dp.getData(),0,dp.getLength()));
- }
- }
- }
复制代码
|