我尝试在Android上实现UDP服务器,我可以将数据包发送到服务器,但无法接收它。此外,我尝试运行接收器没有Android,它的工作原理。问题在哪里?
测试的本地发件人:
int send_packet(uint8_t* data) {
int retcode;
int socket_out;
int broadcast = 1;
struct sockaddr_in addr;
socket_out = socket(AF_INET, SOCK_DGRAM, 0);
if ( socket_out < 0 )
return -1;
setsockopt(socket_out, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof broadcast);
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_BROADCAST);
addr.sin_port=htons(PORT_NUMBER);
retcode = sendto(socket_out, data, sizeof(packet_data_t), 0,
(struct sockaddr *) &addr, sizeof(addr));
perror("sendto");
close(socket_out);
return 0;
}
Android接收器:
public void run(){
try {
byte[] buffer = new byte[BUFFER_SIZE];
DatagramSocket socket = new DatagramSocket(getPort());
//socket.setBroadcast(true);
while(true){
DatagramPacket packet = new DatagramPacket(buffer, buffer.length );
socket.receive(packet);
(new CallbackWrapper(getPacketReciever())).run();
}
} catch (IOException e) {
e.printStackTrace();
}
}
ps我在HTC Legend上运行我的应用程序,而不是在模拟器上运行
答案 0 :(得分:1)
主要问题在于这一行:
DatagramSocket socket = new DatagramSocket(getPort());
您假设设备的本地主机与机器/计算机相同,但设备有自己的网卡,因此在任何网络中都有自己的IP,以及他自己的网络地址IP,这是他自己。只能通过机器的端口访问设备。