android DatagramSocket send 发送数据出错
安卓4.0以后好像不能在主线程里面使用 socket 所以不管是发送数据还是接收数据需要新开一个了线程:
以下代码是我点击发送是代码:
new Thread(new Runnable() {
@Override
public void run() {
try {
sendData();
} catch (Exception e) {
Log.e(_TAG, "Check: Error2: " + e);
} finally {
}
}
}).start();
private void sendData()
{
DatagramSocket socket=null;
try {
socket = new DatagramSocket();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InetAddress serverAddress=null;
try {
serverAddress = InetAddress.getByName("192.168.1.101");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String str = "hello";
byte data[] = str.getBytes();
DatagramPacket pkdata = new DatagramPacket (data , data.length , serverAddress , 8899);
try {
socket.send(pkdata);
} catch (IOException e) {
// TODO Auto-generated catch block
Log.v(null,e.getMessage()+"11111111111");
e.printStackTrace();
}
finally {
if (null != socket) {
socket.close();
socket = null;
}
}
}