我正在尝试在 android 中使用 UDP 套接字,在这里我从 android 模拟器发送我的字符串并通过我的 Java 程序在 PC 上接收它,但是我的 Java 程序没有收到任何东西,尽管当我使用 Java 程序作为客户端和服务器时(我做了两个不同的Java程序)它工作。
这是我的 android 主要活动:
public class First extends Activity {
Button b;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Thread t = new Thread(new Second());
t.start();
}
});
这是我在 android 中的第二堂课:
public class Second implements Runnable {
Second()
{
run();
}
public void run() {
// TODO Auto-generated method stub
try {
String messageStr = "Hello Android!";
int server_port = 9876;
DatagramSocket s = new DatagramSocket();
InetAddress local = InetAddress.getByName("127.0.0.1");
int msg_length = messageStr.length();
byte[] message = messageStr.getBytes();
DatagramPacket p = new DatagramPacket(message, msg_length, local,
server_port);
s.send(p);
} catch (Exception e) {
}
}
}
这是我在 PC 上的 Java 代码:
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData,receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData(),0,receivePacket.getLength());
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
System.out.println("MESSAGE RECEIVED "+sentence+" "+IPAddress+" "+port);
}
}