How to use UDP sockets in android?(如何在android中使用UDP套接字?)
问题描述
我正在尝试在 android 中使用 UDP 套接字,在这里我从 android 模拟器发送我的字符串并通过我的 Java 程序在 PC 上接收,但是我的 Java 程序没有收到任何东西,尽管当我使用 Java 程序作为两个客户端时和服务器(我制作了两个不同的 Java 程序).
I am trying to use UDP sockets in a android, here I send my string from android emulator and receive that by my Java program on PC, but my Java program does not receive anything, although when I used Java program as both client and server (I made two different Java programs) it worked.
这是我的 android 主要活动:
This is my android main activity :
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 中的第二堂课:
Here is my second class in 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 代码:
This is my Java code on PC:
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);
}
}
推荐答案
在您的 Android 仿真(和 Android 设备)上,127.0.0.1 表示 Android 仿真机,而不是主机 PC.您可以在 10.0.2.2
On your Android emulation (and Android device), 127.0.0.1 means the Android emulation machine, not the host PC. You can access your host at 10.0.2.2
这篇关于如何在android中使用UDP套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在android中使用UDP套接字?
基础教程推荐
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01