[英]UDP Sending and Receiving
I've looking into multiple ways to do this and nothing has helped/worked new to Java UDP packets. 我正在研究实现此目的的多种方法,但是对于Java UDP数据包来说,什么都没有帮助/工作。
My code for Android is started via a service and it runs on a new thread. 我的Android代码是通过服务启动的,并在新线程上运行。
Code for waiting: 等待代码:
try {
int port = 58452;
// Create a socket to listen on the port.
DatagramSocket dsocket = new DatagramSocket(port);
// Create a buffer to read datagrams into. If a
// packet is larger than this buffer, the
// excess will simply be discarded!
byte[] buffer = new byte[2048];
// Create a packet to receive data into the buffer
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
// Now loop forever, waiting to receive packets and printing them.
while (true) {
// Wait to receive a datagram
dsocket.receive(packet);
// Convert the contents to a string, and display them
String msg = new String(buffer, 0, packet.getLength());
System.out.println(packet.getAddress().getHostName() + ": "
+ msg);
// Reset the length of the packet before reusing it.
packet.setLength(buffer.length);
}
} catch (Exception e) {
System.err.println(e);
}
Code for sending: 发送代码:
try {
String host = "MY PHONES IP";
int port = 58452; //Random Port
byte[] message = "LAWL,LAWL,LAWL".getBytes();
// Get the internet address of the specified host
InetAddress address = InetAddress.getByName(host);
// Initialize a datagram packet with data and address
DatagramPacket packet = new DatagramPacket(message, message.length,
address, port);
// Create a datagram socket, send the packet through it, close it.
DatagramSocket dsocket = new DatagramSocket();
dsocket.send(packet);
dsocket.close();
System.out.println("Sent");
} catch (Exception e) {
System.err.println(e);
}
}
It sends fine but won't receive on Android. 它可以正常发送,但不会在Android上接收。 Please help!
请帮忙!
Also my Logcat output: http://pastebin.com/Rfw5mSKV 也是我的Logcat输出: http ://pastebin.com/Rfw5mSKV
Thanks -Fusion 谢谢-融合
http://systembash.com/content/a-simple-java-udp-server-and-udp-client/ http://systembash.com/content/a-simple-java-udp-server-and-udp-client/
I used that to and it works! 我习惯了,它起作用了! Thanks to /u/TarkLark or Reddit!
感谢/ u / TarkLark或Reddit!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.