我已经构建了一个upd服务器监听代码,可以在我的手机上上传并收听数据包。此代码将编译但由于某种原因它不会加载到我的手机。我在任何地方都没有看到任何错误。为什么会这样?这是我的整个主要活动代码:
package roman10.tutorial.udpcommserver;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.net.InetSocketAddress;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class UdpServer extends Activity {
/** Called when the activity is first created. */
private TextView textView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView) findViewById(R.id.text1);
runUdpServer();
}
private static final int UDP_SERVER_PORT = 4000;
private static final int MAX_UDP_DATAGRAM_LEN = 1500;
private static final String ipAdd = new String("172.30.42.80");
private void runUdpServer() {
String lText;
// byte[] lMsg = new byte[MAX_UDP_DATAGRAM_LEN];
// DatagramPacket dp = new DatagramPacket(lMsg, lMsg.length);
// DatagramSocket ds = null;
byte buffer[] = new byte[MAX_UDP_DATAGRAM_LEN];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
try {
// ds = new DatagramSocket(UDP_SERVER_PORT);
// //disable timeout for testing
// //ds.setSoTimeout(100000);
// ds.receive(dp);
//lText = new String(lMsg, 0, dp.getLength());
// Log.i("UDP packet received", lText);
// textView.setText(lText);
DatagramSocket s = new DatagramSocket();
InetSocketAddress address = new InetSocketAddress(ipAdd, UDP_SERVER_PORT);
s.bind(address);
lText = new String(buffer,0,packet.getLength());
Log.i("UDP packet received", lText);
textView.setText(lText);
System.out.println("Waiting...");
s.receive(packet);
if (s != null) {
s.close();
}
// s.close();
System.out.println("Received!");
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
System.out.print("we are done ");
}
}
}
答案 0 :(得分:0)
1) 你没有从你的onCreate回来(直到你收到了什么)。活动无法继续开始(当然不会调用onStart,onResume等。
2)
然后你在主线程上进行I / O,甚至是网络I / O,不推荐,并且通常在android上检测不允许并强制关闭。您将获得NetworkOnMainThreadException
幸运的是,这些问题都可以通过创建一个单独的线程并在那里执行runUdpServer()
来解决。
简短的例子,而不是:
runUdpServer();
做的:
Thread thread = new Thread() {
public void run() {
runUdpServer();
}
};
thread.start();