这是我的代码(节点的javascript):
var dgram = require('dgram');
var message = new Buffer("why hello beautiful");
var client = dgram.createSocket("udp4");
client.bind(41234);
client.setBroadcast(true);
client.send(message, 0, message.length, 41234, "134.71.147.255");
console.log('msg sent');
client.close();
这是我的计算机运行节点的ifconfig(我认为唯一相关的事情 - 如果我错了请纠正我):
inet addr:134.71.146.49 Bcast:134.71.147.255 Mask:255.255.254.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
我的iOS应用程序既没有收到udp broacast,也没有通过数据包检查员看到udp broacast。 出了什么问题?! iOS应用程序使用GCDAsyncUdpSocket框架:
- (void) initUDPlistener {
NSLog(@"initUDPlistener");
udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *error = nil;
if (![udpSocket bindToPort:UDP_PORT error:&error]) //does the port matter? i dont know
{
return;
}
if (![udpSocket beginReceiving:&error])
{
return;
}
[udpSocket enableBroadcast:YES error:nil];
[udpSocket sendData:[self pack:@"iOS to bcast"] toHost:UDP_BCAST_ADDR port:UDP_PORT withTimeout:-1 tag:0];
}
#pragma mark -
#pragma mark Delegate UDP methods
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
fromAddress:(NSData *)address
withFilterContext:(id)filterContext
{
NSLog(@"niets.");
NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (msg)
{
NSLog(@"iets gekregen");
}
else
{
NSLog(@"Error convertion");
}
NSLog(@"HMMMM");
}
-(void) udpSocket:(GCDAsyncUdpSocket *) sock didSendDataWithTag:(long)tag {//called. and packet inspector recieves the packet when it is sent OUT from the iOS app.
NSLog(@"written data tag: %ld", tag);
}
-(void) udpSocket:(GCDAsyncUdpSocket *)sock didConnectToAddress:(NSData *)address { //never called
NSLog(@"connected to some address");
}
会发生什么: “didReceiveData”不会从节点广播中调用。但是,当它发送自己的消息时会被调用。
另一方面,iOS应用程序成功广播,我能够拦截我的数据包检查器上的数据包。但是,相同的数据包检查器不会显示应该来自Node的数据包。我在节点中做错了什么?我认为我在节点中所做的是问题。