《黑马程序员》Udp之聊天室

来源:互联网 发布:编程软件mastercam 编辑:程序博客网 时间:2024/06/05 21:49
import java.net.*;import java.io.*;class Send implements Runnable{private DatagramSocket ds;public Send(DatagramSocket ds){this.ds=ds;}public void run(){try{while(true){  //不停的发送//数据BufferedReader br=new BufferedReader(new InputStreamReader(System.in));String line=null;while((line=br.readLine())!=null){byte[] buff=line.getBytes();DatagramPacket dp=new DatagramPacket(buff,buff.length,InetAddress.getByName("192.168.124.171"),10002);ds.send(dp);};}}catch(Exception e){throw new RuntimeException("数据发送失败");}}}class Receive implements Runnable{private DatagramSocket ds;public Receive(DatagramSocket ds){this.ds=ds;}public void run(){try{while(true){  //不停的接收byte[] buff=new byte[1024];DatagramPacket dp=new DatagramPacket(buff,buff.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("数据接收失败");}}}class ChartRoom{/*  UDP聊天软件    有接收与发送的功能 因为接收与发送可以同时执行 所以需要使用多线程技术 又因为接收和发送的数据的内容不同 所以要定义在不同的类中*/public static void main(String[] args) {try{DatagramSocket sds=new DatagramSocket();DatagramSocket rds=new DatagramSocket(10002);new Thread(new Send(sds)).start();new Thread(new Receive(rds)).start();}catch(Exception e){throw new RuntimeException("程序运行发生异常");}}}

0 0