标签:style blog http io ar color os sp java
接着之前的UDP学习.想在单个窗口中实现接收以及发送数据,这个如何实现呢?首先想到的是通过多线程实现发送数据以及接收数据,这样就把问题解决了.下面是代码:
1 import java.net.*; 2 import java.io.*; 3 class UDPSendThread implements Runnable 4 { 5 private DatagramSocket ds=null; 6 public UDPSendThread(DatagramSocket ds) 7 { 8 this.ds=ds; 9 } 10 public void run() 11 { 12 BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 13 String line=null; 14 try 15 { 16 while((line=br.readLine())!=null) 17 { 18 if("886".equals(line)) 19 { 20 break; 21 } 22 byte[]buf=line.getBytes(); 23 DatagramPacket dp=new DatagramPacket(buf,buf.length,InetAddress.getByName 24 25 ("127.0.0.1"),10002); 26 ds.send(dp); 27 } 28 } 29 catch(Exception ex) 30 { 31 System.out.println(ex); 32 throw new RuntimeException("发送失败"); 33 } 34 } 35 } 36 37 class UDPReceiveThread implements Runnable 38 { 39 private DatagramSocket ds=null; 40 public UDPReceiveThread(DatagramSocket ds) 41 { 42 this.ds=ds; 43 } 44 public void run() 45 { 46 47 try 48 { 49 while(true) 50 { 51 byte[] buf=new byte[1024]; 52 DatagramPacket dp=new DatagramPacket(buf,buf.length); 53 ds.receive(dp); 54 String ip=dp.getAddress().getHostAddress(); 55 String data=new String(dp.getData(),0,dp.getLength()); 56 System.out.println(ip+"......"+data); 57 58 } 59 } 60 catch(Exception ex) 61 { 62 throw new RuntimeException("接收失败"); 63 } 64 } 65 } 66 67 class UDPThreadDemo 68 { 69 public static void main(String[]args) throws Exception 70 { 71 DatagramSocket dsSend=new DatagramSocket(); 72 DatagramSocket dsReceive=new DatagramSocket(10002); 73 new Thread(new UDPSendThread(dsSend)).start(); 74 new Thread(new UDPReceiveThread(dsReceive)).start(); 75 } 76 }
通过dos命令行,编译程序,运行,便可以在单个窗口实现发送与接收数据了,如下:
标签:style blog http io ar color os sp java
原文地址:http://www.cnblogs.com/LenLi/p/4149660.html