送信側クラスと受信側クラスの 2 つのクラスがあります。送信アプリと受信アプリの両方が数秒後に停止し、終了します。私の送信者クラスは次のとおりです。
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 = "0123456789".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());
}
助けてくれてありがとう。