标签:blog http io java ar 数据 2014 on c
先上客户端代码
package com.test.net; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class UDPClient { /** *UDP客户端 */ public static void main(String[] args) throws Exception { DatagramSocket socket=new DatagramSocket(); String str="hello"; byte[] buf=str.getBytes(); DatagramPacket packet=new DatagramPacket(buf,buf.length,InetAddress.getByName("127.0.0.1"),1111); /*直接发包*/ socket.send(packet); } }
package com.test.net; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; public class UDPServer { /** *UDP服务器 */ public static void main(String[] args) throws Exception { DatagramSocket socket=new DatagramSocket(1111); byte[] buf=new byte[256]; DatagramPacket packet=new DatagramPacket(buf,buf.length); /*监听,阻塞*/ socket.receive(packet); String received=new String(packet.getData()); System.out.println(received); } }
在服务器中,DatagramPacket的receive方法会阻塞,相当于监听,一直到监听到数据报为止。
输出结果
结果就是服务器端输出了hello。
标签:blog http io java ar 数据 2014 on c
原文地址:http://blog.csdn.net/itbuluoge/article/details/39502989