我正在尝试在Android中实现基本的数据报套接字。我从网上提供的一个样本开始:
String messageStr="Hello Android!";
int server_port = 54372;
try {
DatagramSocket s = new DatagramSocket();
InetAddress local = null;
local = InetAddress.getByName("192.168.100.127");
int msg_length=messageStr.length();
byte[] message = messageStr.getBytes();
DatagramPacket p = new DatagramPacket(message, msg_length, local, server_port);
s.send(p);
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
我在AndroidManifest.xml中启用了INTERNET权限:
<uses-permission android:name="android.permission.INTERNET"/>
程序在命中s.send(p)
命令时会死亡。
我错过了什么?它必须是明显的东西。
答案 0 :(得分:1)
您收到的错误是您没有抓到的:NetworkOnMainThreadException。 您应该在另一个Thread或AsyncTask中执行所有网络人员。
例如:
class MyThread extends Thread
{
@Override
public void run()
{
UDPSend();
}
void UDPSend()
{
String messageStr = "Hello Android!";
int server_port = 54372;
try
{
DatagramSocket s = new DatagramSocket();
InetAddress local = null;
local = InetAddress.getByName("192.168.1.57");
int msg_length = messageStr.length();
byte[] message = messageStr.getBytes();
DatagramPacket p = new DatagramPacket(message, msg_length, local, server_port);
s.send(p);
android.util.Log.w("UDP", "Works fine!");
}
catch (SocketException e)
{
e.printStackTrace();
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (Exception e)
{
android.util.Log.w("UDP", "Catched here.");
e.printStackTrace();
}
}
}
在主线程中执行线程:new MyThread().start();
更新:
Asynctask中的UDP接收器: 这是一个应用程序的真实示例。我删除了一些不相关的行。 我向您展示了接收UDP数据包的doInBackgroud。
@Override
protected Void doInBackground(Void... urls)
{
DatagramSocket socketUDP;
try
{
socketUDP = new DatagramSocket(5050);
socketUDP.setSoTimeout(5000);
// set it to true if you want to receive broadcast packets
socketUDP.setBroadcast(false);
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
byte[] buff = new byte[512];
DatagramPacket packet = new DatagramPacket(buff, buff.length);
try
{
asyncTask_UDP_is_running=true;
// Keep running until application gets inactive
while (aplicationActive)
{
try
{
socketUDP.receive(packet);
android.util.Log.w("UDP", "got a packet");
}
catch (java.net.SocketTimeoutException ex)
{
// timeout
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
}
finally
{
asyncTask_UDP_is_running=false;
}
return null;
}
}