📄 例11-8.txt
字号:
1)广播数据报的主机
BroadCast.java
import java.net.*;
public class BroadCast extends Thread{
String s="中国奥运代表团已经获得58枚金牌";
int port=5858; //组播的端口
InetAddress group=null; //组播组
MulticastSocket socket=null; //多点广播套接字
BroadCast(){
try{ group=InetAddress.getByName("239.255.8.0"); //设置组播组为239.255.8.0
socket=new MulticastSocket(port); //多点广播套接字将在port端口广播
socket.setTimeToLive(0); //多点广播套接字发送数据报范围为本地网络
socket.joinGroup(group);
//加入组播组,加入group后,socket发送的数据报可以被加入到group中的成员接收到
}
catch(Exception e){}
}
public void run(){
while(true){
try{ DatagramPacket packet=null; //待广播的数据报
byte data[]=s.getBytes();
packet=new DatagramPacket(data,data.length,group,port);
System.out.println(new String(data));
socket.send(packet); //广播数据报
sleep(2000);
}
catch(Exception e){}
}
}
public static void main(String args[]){
new BroadCast().start();
}
}
2)接收数据报的主机
Receive.java
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Receive extends JFrame implements Runnable,ActionListener{
int port; //组播的端口
InetAddress group=null; //组播组的地址
MulticastSocket socket=null; //多点广播套接字
JButton startReceive,stopReceive;
JTextArea showArea;
Thread thread; //负责接收信息的线程
boolean stop=false;
public Receive(){
super("定时接收信息");
thread=new Thread(this);
startReceive=new JButton("开始接收");
stopReceive=new JButton("停止接收");
startReceive.addActionListener(this);
stopReceive.addActionListener(this);
showArea=new JTextArea(10,10);
JPanel north=new JPanel();
north.add(startReceive);
north.add(stopReceive);
Container con=getContentPane();
con.add(north,BorderLayout.NORTH);
con.add(new JScrollPane(showArea),BorderLayout.CENTER);
port=5858;
try{ group=InetAddress.getByName("239.255.8.0");
socket=new MulticastSocket(port);
socket.joinGroup(group);
}
catch(Exception e){}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(320,300);
validate();
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==startReceive){
if(!(thread.isAlive())){
thread=new Thread(this);
stop=false;
}
try{ thread.start();
}
catch(Exception ee){}
}
if(e.getSource()==stopReceive){
stop=true;
}
}
public void run(){
while(true){
byte data[]=new byte[8192];
DatagramPacket packet=null;
packet=new DatagramPacket(data,data.length,group,port);
try { socket.receive(packet);
String message=new String(packet.getData(),0,packet.getLength());
showArea.append("\n"+message);
showArea.setCaretPosition(showArea.getText().length());
}
catch(Exception e){}
if(stop==true)
break;
}
}
public static void main(String args[]){
new Receive();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -