各位版友好,
因实验需要,动手写了一个简易的Udp Server,目的是在笔电上,
透过外接无线网卡连线,收到同个网域设备的讯息之后,睡一段时间,再将讯息中第一
个数值+1后回传,
希望server收到设备传来的讯息后,能够用一个新的thread执行睡+传讯息的功能,并将
此thread丢到一个上限为5的thread pool,
为了防止设备睡着,在传讯息前,server会先不断ping设备,若设备醒了才传讯息,
工具执行后,发现只执行到收到设备传给server的消息后,印出后工具就不动了,想请教
是否我哪里写错了呢?
执行结果:
https://i.imgur.com/VcEj4HX.jpg
完整Code连结:https://reurl.cc/q8OggR
部分Code-1(处理收到讯息的机制)
SD.Initial(port,interval);
SD.ShowConnectInfo();
try
{
while(true)
{
SD.socket.receive(SD.packet);
String msg=new String(SD.buf, 0, SD.packet.getLength());
if(!msg.isEmpty())
{
SD.AddLog(SD.packet.getAddress().getHostAddress(),"Read",
msg);
if(msg.equals("End"))
{
SD.IpList.remove(SD.packet.getAddress().getHostAddress
());
if(SD.IpList.isEmpty())
break;
}
else
{
String times=String.valueOf(Integer.parseInt(msg.split
(",")[0])+1);
SD.AddTask(SD.packet.getAddress().getHostAddress(), SD
.packet.getPort(), times);
}
}
}
}catch(Exception e)
{
e.printStackTrace();
}
部分Code-2(thread的runnable内容)
esAddTask=Executors.newFixedThreadPool(5);
public void AddTask(String ip,int port,String msg)
{
esAddTask.execute(genTask(ip,port,msg));
}
private Runnable genTask(String ip, int port, String msg)
{
return new Runnable(){
public void run()
{
AddLog(packet.getAddress().getHostAddress(), "Info", "Sleep "+
interval+" sec.");
try
{
Thread.sleep(interval*1000);
Ping(packet.getAddress().getHostAddress());
socket.send(new DatagramPacket(msg.getBytes(), msg.length(
),packet.getAddress(),packet.getPort()));
}catch(Exception e)
{
e.printStackTrace();
}
}
};
}
private void Ping(String ip)
{
String line=null;
String ping=String.format("ping -n 1 -w 1000 %s",ip);
try{
Process process=Runtime.getRuntime().exec(ping);
BufferedReader br=new BufferedReader(new InputStreamReader(process
.getInputStream(),"Big5"));
while((line=br.readLine())!=null)
{
if(!line.isEmpty())
{
if ((line.contains("Reply from " + ip)line.contains("回复
自 " + ip)))
{
AddLog(ip, "Info", "Ping successed.");
}
else if(line.contains("Request timed out.") line.contains
("要求等候逾时"))
{
AddLog(ip, "Info", "Ping Failed.");
Thread.sleep(1000);
Ping(ip);
}
}
}
}catch(Exception e)
{
e.printStackTrace();
}
}