接收端:
1 package WebProgramingDemo; 2 3 import java.net.DatagramPacket; 4 import java.net.DatagramSocket; 5 6 public class CharReceivePart implements Runnable{ 7 8 private DatagramSocket ds; 9 public CharReceivePart(DatagramSocket ds) { 10 this.ds=ds; 11 } 12 @Override 13 public void run() { 14 try{ 15 while(true){ 16 byte[] buf=new byte[1024]; 17 DatagramPacket dp1=new DatagramPacket(buf, buf.length); 18 ds.receive(dp1); 19 String ip=dp1.getAddress().getHostAddress(); 20 int port=dp1.getPort(); 21 String text=new String(dp1.getData(),0,dp1.getLength()); 22 System.out.println(ip+"::"+port+"::"+text); 23 } 24 }catch(Exception e){ 25 26 } 27 } 28 29 30 31 }
发送端:
1 package WebProgramingDemo; 2 3 import java.io.BufferedReader; 4 import java.io.InputStreamReader; 5 import java.net.DatagramPacket; 6 import java.net.DatagramSocket; 7 import java.net.InetAddress; 8 9 public class ChartSendPart implements Runnable { 10 11 DatagramSocket ds2; 12 public ChartSendPart(DatagramSocket ds2) { 13 this.ds2=ds2; 14 } 15 @Override 16 public void run() { 17 try{ 18 BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in)); 19 String line=null; 20 while((line=bufr.readLine())!=null){ 21 byte buf[]=new byte[1024]; 22 DatagramPacket dp2=new DatagramPacket(buf, buf.length,InetAddress.getByName("192.168.2.255"),10001); 23 ds2.send(dp2); 24 } 25 }catch(Exception e){ 26 27 } 28 } 29 30 31 32 }
主类:
1 package WebProgramingDemo; 2 3 import java.io.IOException; 4 import java.net.DatagramSocket; 5 6 public class ChartDamo { 7 8 /** 9 * @param args 10 * @throws IOException 11 */ 12 public static void main(String[] args) throws IOException { 13 14 DatagramSocket send=new DatagramSocket(); 15 DatagramSocket receive=new DatagramSocket(10001); 16 new Thread(new ChartSendPart(send)).start(); 17 new Thread(new CharReceivePart(receive)).start(); 18 } 19 20 }