在第一种方法中,我创建了基于sampleProject的客户端-服务器应用程序,它将一些数据发送到服务器。
Legend:
sender
address = reciver ip
port = reciver port
reciver
address = null since he is listening
port = in my case 55555
工作代码
仅出于公共原因故意跳过错误检查
发件人
-(id*)initForSender:(NSString*)address port:(int)port
{
self = [super init];
if (self) {
_port = port;
_address = address;
tag = 0;
_udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
[_udpSocket bindToPort:0 error:&error];
[_udpSocket beginReceiving:&error];
return self;
}
}
-(void)send:(NSData*)data{
[_udpSocket sendData:data toHost:_address port:_port withTimeout:-1 tag:tag];
tag++;
}
接收器/监听器
-(id*)initForReceiver:(NSString*)address port:(int)port
{
self = [super init];
if (self) {
_port = port;
_udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *error = nil;
[_udpSocket bindToPort:0 error:&error];
[_udpSocket beginReceiving:&error];
}
return self;
}
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
fromAddress:(NSData *)address
withFilterContext:(id)filterContext
{
//Do something with receive data
}
组播
但后来我想要将发送给许多接收者的客户端。我知道 sendre 或 listener 应该使用 [GCDAsyncUdpSocket joinMulticastGroup:error]; 的表单。我通过 stackoverflow、google 叔叔和 CococaAsyncSocket(没有关于 udp 的词)运行,匹配收集到的信息并想出了这段代码。我完全确定,这不起作用,但我不知道为什么。
Legend:
sender
address = sender ip
port = sender port in my case 55555
reciver
address = sender ip
port = sender port in my case 55555
不工作的代码
-(id*)initForSender:(NSString*)address port:(int)port
{
self = [super init];
if (self) {
_port = port;
_address = address;
_udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *error = nil;
[_udpSocket bindToPort:_port error:&error];
[_udpSocket joinMulticastGroup:_address error:&error];
[_udpSocket enableBroadcast:YES error:&error];
}
return self;
}
-(void)send:(NSData*)data{
[_udpSocket sendData:data toHost:_address port:_port withTimeout:-1 tag:tag];
tag++;
}
接收器/监听器
-(id*)initForReceiver:(NSString*)address port:(int)port
{
self = [super init];
if (self) {
_port = port;
_address = address;
_udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *error = nil;
[_udpSocket bindToPort:_port error:&error];
[_udpSocket joinMulticastGroup:_address error:&error];
[_udpSocket beginReceiving:&error])
}
return self;
}
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
fromAddress:(NSData *)address
withFilterContext:(id)filterContext
{
//Do something with receive data
}
更新:
事实证明,当我使用一些未使用的 IPaddress
例如@“224.0.1.1”时,它会工作,但感觉有点奇怪。我做对了吗?