标签:
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(); } }
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(); }
标签:
原文地址:http://www.cnblogs.com/ShengXi-1994/p/5581109.html