首页 > 代码库 > java之UDP(datagramsocket,datagramPacket)实例
java之UDP(datagramsocket,datagramPacket)实例
import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.Socket; import java.net.SocketException; import java.net.UnknownHostException; import org.junit.Test; public class TestUDP { @Test public void send() throws Exception{ String str = "Hello"; DatagramPacket pack = new DatagramPacket(str.getBytes(),str.getBytes().length,InetAddress.getByName("127.0.0.1"),10000); DatagramSocket scoket = new DatagramSocket(); for(int i =0; i< 10;i++){ scoket.send(pack); } scoket.close(); } @Test public void revice() throws Exception{ byte[] by = new byte[1024]; DatagramPacket pack = new DatagramPacket(by,by.length); DatagramSocket scoket = new DatagramSocket(10000); while(true){ scoket.receive(pack); System.out.println(new String(pack.getData())); } } }
java之UDP(datagramsocket,datagramPacket)实例
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。