我正在制作一个非常简单的应用程序,在其中我从我的 PC 上的 java 程序发送一个文本字符串,我试图从我的模拟器中的 android 应用程序接收相同的字符串。
这是我的活动(服务器):
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_appstart);
tv = (TextView) findViewById(R.id.textView1);
try {
DatagramSocket clientsocket = new DatagramSocket(9876);
byte[] receivedata = new byte[1024];
DatagramPacket recv_packet = new DatagramPacket(receivedata, receivedata.length);
Log.d("UDP", "S: Receiving 1 sec...");
clientsocket.receive(recv_packet);
String rec_str = new String(recv_packet.getData());
tv.setText(rec_str);
Log.d(" Received String ", rec_str);
InetAddress ipaddress = recv_packet.getAddress();
int port = recv_packet.getPort();
Log.d("IPAddress : ", ipaddress.toString());
Log.d(" Port : ", Integer.toString(port)); clientsocket.close();
} catch (Exception e) {
Log.e("UDP", "S: Error", e);
}
}
这是我的PC客户端java代码:
public static void main(String args[]) throws Exception
{
while(true)
{
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("127.0.0.1");
System.out.println(IPAddress.getHostName());
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData,sendData.length,IPAddress,9876);
clientSocket.send(sendPacket);
System.out.println(sendPacket.getPort());
clientSocket.close();
}
}
onReceive()
然而,该应用程序没有收到任何东西,但在 android 应用程序中的函数上抛出异常......
有谁知道为什么?