📄 multicastserver.java
字号:
import java.io.*;
import java.net.*;
import java.util.*;
public class MulticastServer{
public static void main(String args[]) throws java.io.IOException{
new MulticastServerThread().start();
//启动一个服务器线程
}
}
class MulticastServerThread extends Thread{
DatagramSocket socket;
DatagramPacket packet;
InetAddress group;
BufferedReader bf;
//private boolean token=true;
private long FIVE_SECONDS=5000; //定义常量,5秒钟
public MulticastServerThread() throws IOException{
this("MulticastServerThread");
//调用父类,也就是QuoteServerThread的构造函数
}
public MulticastServerThread(String name){
super(name);
try{
socket=new DatagramSocket(4001);
group=InetAddress.getByName("230.0.0.1");
}catch(Exception e){}
try{
bf=new BufferedReader(new FileReader("data.txt"));
}catch(Exception e){System.out.println("File not found!");}
}
public void run() //重写父类的线程主体
{
int count=0;
String allData="";
boolean token=true;
try{
String line=bf.readLine();
while(line!=null){
allData+=line+"\n";
line=bf.readLine();
}
while(token){
try{
byte [] data=allData.getBytes();
packet=new DatagramPacket(data,data.length,group,4001);
socket.send(packet);
System.out.println(count=count+1);
try{
sleep((long)(Math.random()*FIVE_SECONDS));
}catch(Exception e){}
if(count>20) token=false;
}catch(Exception e){}
}
socket.close();
bf.close();
}catch(Exception e){}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -