各位版友好,
因實驗需要,動手寫了一個簡易的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();
}
}