UDP:
无连接协议
udp协议发送数据,用的是数据报包的形式。(64KB以内)
发送端:
1.定义发送的datagramsocket对象,发送端可以不用定义端口
2.定义封装数据包datagrampacket
3.发送数据包
4.关闭资源
//InetAddress.getByName("192.168.3.255")必须是统一的网段
public class UdpSendThread implements Runnable { DatagramSocket ds; byte[] buf; public UdpSendThread(DatagramSocket ds) { this.ds = ds; } public UdpSendThread(DatagramSocket ds, String str) { this.ds = ds; this.buf = str.getBytes(); } @Override public void run() { String brStr; try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in, "utf-8")); while ((brStr = br.readLine()) != null) { if(brStr.startsWith("@")){ } DatagramPacket dp = new DatagramPacket(brStr.getBytes(), brStr.getBytes().length, InetAddress.getByName("192.168.3.255"), 9000); ds.send(dp); if (brStr.equals("over")) { break; } } //br.close(); ds.close(); } catch (UnknownHostException | UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
接收端:
1、建立DatagramSocket对象
2、定义一个空的数据包
3、接受数据包
4、解析数据包
5、关闭资源
public class UdpRececiveThread extends Thread { DatagramSocket ds; public UdpRececiveThread(DatagramSocket ds) { this.ds = ds; } @Override public void run() { while(true){ byte[] buf = new byte[1024*1024]; DatagramPacket dp = new DatagramPacket(buf, buf.length); try { ds.receive(dp); String ip = dp.getAddress().getHostAddress(); String content = new String(dp.getData(),0,dp.getLength()); if(content.equals("over")){ System.out.println(ip+"退出"); } System.out.println(ip+":"+content); } catch (IOException e) { e.printStackTrace(); } } } }
测试类:
public static void main(String[] args) throws SocketException { DatagramSocket sendDs = new DatagramSocket(); DatagramSocket reDs = new DatagramSocket(9000); new Thread(new UdpSendThread(sendDs)).start();; new UdpRececiveThread(reDs).start(); }
时间: 2024-11-04 06:42:42