我有兩個類,一個發件人類,另一個是接收者類。發送和接收應用程序都在幾秒鐘後停止並關閉。 我的發件人類是:發送和接收數據報套接字上的UDP數據包android
public class MainActivity extends Activity {
InetAddress receiverAddress;
DatagramSocket datagramSocket;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
datagramSocket = new DatagramSocket(4444);
} catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte[] buffer = "".getBytes();
byte[] address="192.168.1.101".getBytes();
try {
receiverAddress = InetAddress.getByAddress(address);
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
DatagramPacket packet = new DatagramPacket(
buffer, buffer.length, receiverAddress, 4444);
try {
datagramSocket.send(packet);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
我接收或聽力課是:事先的幫助
public class MainActivity extends Activity {
DatagramSocket datagramSocket;
DatagramPacket packet;
TextView tv1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1=(TextView)findViewById(R.id.textView1);
try {
datagramSocket = new DatagramSocket(80);
} catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte[] buffer = new byte[10];
packet = new DatagramPacket(buffer, buffer.length);
try {
datagramSocket.receive(packet);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] buff = packet.getData();
tv1.setText(buff.toString());
}
感謝。
我認爲你必須在單獨的線程或新線程上運行這些數據報事務,儘管我不確定這是否能解決你的問題 – kabuto178
你的logcat中有什麼? –