UDT接收发送广播

来源:互联网 发布:mac sogo拼音输入法 编辑:程序博客网 时间:2024/05/29 10:45
public class Weather extends Thread{String weather="节目预报:八点有大型晚会,请收听";int port=9898;//端口号InetAddress iaddress=null;MulticastSocket socket=null;//声明多点广播套接字Weather(){//构造方法try{iaddress=InetAddress.getByName("224.255.10.0");//实例化对象指定地址socket=new MulticastSocket(port);//实例化对象socket.setTimeToLive(1);//指定发生范围为本地网络socket.joinGroup(iaddress);//加入广播组}catch(Exception e){e.printStackTrace();}}public void run(){while(true){DatagramPacket packet=null;//byte data[]=weather.getBytes();//创建字节数组packet=new DatagramPacket(data, data.length,iaddress,port);//将数据打包System.out.println(new String(data));//讲广播信息输出try{socket.send(packet);//发送数据Thread.sleep(3000);}catch(Exception e){e.printStackTrace();}}} public static void main(String[] args) { Weather w=new Weather(); w.start();}}

public class Receive extends JFrame implements Runnable,ActionListener{int port;InetAddress group=null;MulticastSocket socket=null;//创建多点广播套接字JButton ince=new JButton("开始接收");JButton stop=new JButton("停止接收");JTextArea inceAr=new JTextArea(10,10);JTextArea inced=new JTextArea(10,10);Thread thread;boolean b=false;public Receive(){//构造方法super("广播数据包");setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);thread=new Thread(this);ince.addActionListener(this);//添加事件监听stop.addActionListener(this);inceAr.setForeground(Color.blue);//设置文本域文字颜色JPanel north=new JPanel();//创建北边的面板north.add(ince);north.add(stop);add(north,BorderLayout.NORTH);//添加到面板JPanel center=new JPanel();//创建中间的面板center.setLayout(new GridLayout(1,2));center.add(inceAr);center.add(inced);add(center, BorderLayout.CENTER);validate();//刷新port=9898;//端口号try{group=InetAddress.getByName("224.255.10.0");socket=new MulticastSocket(port);//绑定多点广播她接着socket.joinGroup(group);//加入广播组}catch(Exception e){e.printStackTrace();}setBounds(100,50,360,380);setVisible(true);}public void run(){while(true){byte data[]=new byte[1024];//创建数组DatagramPacket packet=null;packet=new DatagramPacket(data, data.length,group,port);//打包数据try{socket.receive(packet);//接收数据包String message=new String(packet.getData(),0,packet.getLength());//获取数据包中内容inceAr.setText("正在接受的内容:\n"+message);;//将接受内容显示 在文本域inced.append(message+"\n");//每条信息为一行}catch(Exception e){e.printStackTrace();}if(b==true){break;}}}public void actionPerformed(ActionEvent e){if(e.getSource()==ince){ince.setBackground(Color.red);//设置颜色stop.setBackground(Color.yellow);if(!(thread.isAlive())){thread=new Thread(this);}thread.start();b=false;}if(e.getSource()==stop){ince.setBackground(Color.yellow);stop.setBackground(Color.red);b=true;}}public static void main(String[] args) {Receive rec=new Receive();rec.setSize(460,200);}}

原创粉丝点击