1
我試圖編寫一個簡單的可以發送和接收數據的UDP客戶端,並且我想將委託設置爲自身以外的另一個對象。將代表設置爲Cocoaasyncsocket中的另一個對象
我能夠發送數據但無法從服務器接收任何迴應。服務器工作正常。
我的代碼如下:
//ViewController.m
- (void)setupSocket
{
UDPReveiver * udp = [[UDPReveiver alloc] init];
udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:udp delegateQueue:dispatch_get_main_queue()];
NSError *error = nil;
if (![udpSocket bindToPort:5528 error:&error])
{
NSLog(@"Error binding: %@", error);
return;
}
if (![udpSocket beginReceiving:&error])
{
NSLog(@"Error receiving: %@", error);
return;
}
NSLog(@"Socket Created :)");
}
//UDPReceiver.h
@interface UDPReveiver : NSObject <GCDAsyncUdpSocketDelegate>
//UDPReceiver.m
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
fromAddress:(NSData *)address
withFilterContext:(id)filterContext
{
NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Hey");
if (msg)
{
NSLog(@"Data received is :%@",msg);
}
}
請讓我知道我錯過了什麼。
謝謝丹現在完美的作品。 –