import java.io.IOException;
import java.net.*;
public class Notification extends Thread{
String weather="节目预报:八点有大型晚会,请收听";
int port=9898;
InetAddress iaddress=null;
MulticastSocket socket=null;
Notification(){
try {
iaddress=InetAddress.getByName("224.255.10.0");
socket=new MulticastSocket(port);
socket.setTimeToLive(1);
socket.joinGroup(iaddress);
}catch(IOException 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(weather);
try {
socket.send(packet);
sleep(3000);
}catch(IOException e)
{
e.printStackTrace();
}catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Notification w=new Notification();
w.start();
}
}
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.net.*;
import javax.swing.*;
public class Receive extends JFrame implements Runnable,ActionListener{
int port;
InetAddress group=null;
MulticastSocket socket=null;
JButton inceBtn=new JButton("停止接收");
JButton stopBtn=new JButton("开始接收");
JTextArea inceAr=new JTextArea(10,10);
JTextArea inced=new JTextArea(10,10);
Thread thread;
boolean stop=false;
public Receive()
{
setTitle("广播数据报");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
thread=new Thread(this);
inceBtn.addActionListener(this);
stopBtn.addActionListener(this);
inceAr.setForeground(Color.blue);
JPanel north=new JPanel();
north.add(inceBtn);
north.add(stopBtn);
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(IOException e)
{
e.printStackTrace();
}
setBounds(100,50,360,380);
setVisible(true);
}
public void run()
{
while(!stop) {
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(IOException e)
{
e.printStackTrace();
}
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==inceBtn)
{
inceBtn.setBackground(Color.red);
stopBtn.setBackground(Color.yellow );
if(!(thread.isAlive()))
{
thread=new Thread(this);
}
thread.start();
stop=false;
}
if(e.getSource()==stopBtn)
{
inceBtn.setBackground(Color.yellow);
stopBtn.setBackground(Color.red);
stop=true;
}
}
public static void main(String[] args) {
Receive rec=new Receive();
rec.setSize(460,200);
}
}
inceAr.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
inceAr.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);