你好,我的服务有问题。 我正在创建一个实现UDPServer的应用程序,并在接收到的数据包中记录主要活动。即使活动已关闭,我希望服务启动,所以我认为我必须使用服务。这是真的吗? 我已经意识到一个应用程序实现了一个没有问题的音乐播放器服务,但是当在服务onStart函数中插入UDP服务器的代码我的应用程序粉碎。 这是关于udp服务器的代码:
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
//Create the socket using the serverAddress
//notifica("STARTING SERVER!", "UDP***Creating server" );
//System.out.println("UDP***Creating server");
DatagramSocket socket = new DatagramSocket(SERVERPORT, serverAddr);
//create a buffer to copy packet contents into
byte[] buf = new byte[260];
//create a packet to receive
DatagramPacket packet = new DatagramPacket(buf, buf.length);
notifica("START!", "Server started!" );
while(true) {
try{
socket.receive(packet);
System.out.println("UDP***" + new String(packet.getData()));
notifica("RECEIVED!", new String(packet.getData()) );
} catch (Exception e) {
notifica("EXC_INT:", "UDP Received Exception! " + e.toString() );
}
}
我认为问题在于命令:
socket.receive(packet);
它会阻止执行并等待读取内容。 我希望主程序不会阻止等待服务。
我尝试在服务中插入超时和睡眠命令而没有任何结果:
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
//Create the socket using the serverAddress
//notifica("STARTING SERVER!", "UDP***Creating server" );
//System.out.println("UDP***Creating server");
DatagramSocket socket = new DatagramSocket(SERVERPORT, serverAddr);
//create a buffer to copy packet contents into
byte[] buf = new byte[260];
//create a packet to receive
DatagramPacket packet = new DatagramPacket(buf, buf.length);
notifica("START!", "Server started!" );
while(true) {
try{
socket.setSoTimeout( 100 );
socket.receive(packet);
System.out.println("UDP***" + new String(packet.getData()));
notifica("RECEIVED!", new String(packet.getData()) );
} catch (SocketTimeoutException e) {
//notifica("EXC:", "UDP No data received!" );
//Toast.makeText(getApplicationContext(), "UDP No data received!", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
notifica("EXC_INT:", "UDP Received Exception! " + e.toString() );
}
try{
Thread.sleep(30000);
} catch (Exception e) {
notifica("EXC_INT_TIMER:", "Thread sleep exc! " + e.toString() );
}
}
谢谢!
答案 0 :(得分:0)
如果您不希望主程序在socket.receive(数据包)上阻塞,则必须实现线程;
这样做的一种方法是将阻止代码放在此处:
new Thread(){
public void run(){
//在此处设置阻止代码,例如
while(true){
try{
socket.setSoTimeout( 100 );
socket.receive(packet);
System.out.println("UDP***" + new String(packet.getData()));
notifica("RECEIVED!", new String(packet.getData()) );
} catch (SocketTimeoutException e) {
//notifica("EXC:", "UDP No data received!" );
//Toast.makeText(getApplicationContext(), "UDP No data received!", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
notifica("EXC_INT:", "UDP Received Exception! " + e.toString() );
}
try{
Thread.sleep(30000);
} catch (Exception e) {
notifica("EXC_INT_TIMER:", "Thread sleep exc! " + e.toString() );
}
}
}
}开始();
此外,如果您设置超时和睡眠以解决问题,请将其删除,因为它无法解决您的崩溃问题。