需求:编写一个聊天程序;
功能: 有接收数据的部分,有发送数据的部分,这两部分需要同时执行,也就是说需要用到多线程技术。一个线程控制数据的接收,另一个线程控制数据的发送。
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; public class ChatDemo { public static void main(String[] args) throws SocketException { DatagramSocket sendSocket=new DatagramSocket(); DatagramSocket reciveSocket=new DatagramSocket(10001); new Thread(new Send(sendSocket)).start(); new Thread(new Recive(reciveSocket)).start(); } } //因为接收和发送是不一致,所有要定义两个run方法。而且这两个方法要封装到不同的类中。 class Send implements Runnable{ private DatagramSocket ds; Send(DatagramSocket ds){ this.ds=ds; } public void run() { try { BufferedReader buff=new BufferedReader(new InputStreamReader(System.in)); String line=null; while((line=buff.readLine())!=null){ if("886".equals(line)) break; byte[] buf=line.getBytes(); DatagramPacket dp=new DatagramPacket(buf, buf.length,InetAddress.getByName("10.1.9.34"),10001); ds.send(dp); } } catch (Exception e) { throw new RuntimeException("发送端失败!"); } } } class Recive implements Runnable{ private DatagramSocket ds; Recive(DatagramSocket ds){ this.ds=ds; } public void run() { try { while(true){ byte[] buf=new byte[1024]; DatagramPacket dp=new DatagramPacket(buf, buf.length); ds.receive(dp); String ip=dp.getAddress().getHostAddress(); String data=new String(dp.getData(),0,dp.getLength()); System.out.println(ip+"::"+data); } } catch (Exception e) { throw new RuntimeException("接收端失败!"); } } }运行结果为: