网络编程学习笔记(三)UDP

1、不可靠的、效率高、数据报(数据打成一个小包一个小包地往外发)、非连接。
2、UDP是非连接的,因此严格来说并不区分服务器端和客户端。
3、UDP通信过程:UDP都是通过字节数组进行对话的。
     "服务器"端:接数据
          (1)新建字节数组,用来接收对方发过来的数据
               byte buf[] = new byte[1024];
          (2)创建数据包Socket
               DatagramSocket ds = new DatagramSocket(5678);//端口号5678是udp的5678,TCP还有一个端口5678
          (3)新建包裹DatagramPacket ,包裹把byte字节数组都占满了,第二个参数表示包裹在数组中占的长度。当调用receive()方法接收数据时,将接收到的内容存放到字节数组buf中。
               DatagramPacket  dp = new DatagramPacket (buf, buf.length);
          (4)接收对方发来的数据,有人发数据,就把数据放在包袱里,receive也是阻塞式的方法,如果没有人发数据,就一直等着。
               ds.receive(dp);
               System.out.println(new String(buf,0,dp.getLength()));//把包袱里有的内容转换成字符串输出String(buf,0,dp.getLength())表示通过数组的一部分构建字符串。dp.getLength() 表示字节数组里到底占用了多少空间。
                ds.close();
     “客户”端:发数据
            (1) 将要发送的内容转换成字节数组
               byte[] buf = (new String("Hello")).getBytes();
            (2)创建包裹,并把字节数组放进去,InetSocketAddress是SocketAddress的子类表示Ip地址。
               DatagramPacket dp = new DatagramPacket(buf, buf.length, new InetSocketAddress("127.0.0.1", 5678));
            (3)创建数据包Socket
               DatagramSocket ds = new DatagramSocket(9999);//9999是客户端的端口
            (4)发送信息
               ds.sent(dp);
               ds.close();
          以上例子中传的是String字符串类型的消息;如果要传Long类型的消息,需要通过ByteArrayOutputStream来传消息;服务器端接收时用ByteArrayInputStream。
          客户端:long n = 1000L;
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          DataOutputStream dos = new DataOutputStream(baos );//为了写入long型的数据,采用DataOutputStream处理流
          dos.writeLong(n);//向字节数组输出流中写数据
          byte[]  buf = baos.toByteArray();//将流中的内容转换成字节数组,进而创建DatagramPacket,并用UDP的 DatagramSocket发出消息。
          接下来与上面的例子一致。
          服务器端:
          ds.receive(dp);
          ByteArrayInputStream bais = new ByteArrayInputStream(buf);
          DataInputStream dis = new DataInputStream(bais);
          System.out.println(dis.readLong());
注意:在UDP中用的最多的流就是ByteArrayOutputStream、DataOutputStream和ByteArrayInputStream、DataInputStream
原文地址:https://www.cnblogs.com/bjh1117/p/6393710.html