Socket 通信中,TCP/UDP,接着UDP的方法:
- (void)initSendSocket
{
if (!_sendTextUdpSocket) {
_sendTextUdpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
}
NSError *error = nil;
if (![_sendTextUdpSocket bindToPort:PORT error:&error])
{
NSLog(@"Error binding(_sendTextUdpSocket):%@", error);
return;
}
if (![_sendTextUdpSocket beginReceiving:&error])
{
NSLog(@"Error receiving(_sendTextUdpSocket): %@", error);
return;
}
NSLog(@"_sendTextUdpSocket ready!");
}
//2、实现代理方法
//发送成功回调方法
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didSendDataWithTag:(long)tag
{
NSLog(@"did Send Data");
}
//发送失败回调方法
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error
{
NSLog(@"did Not Send Data");
}
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext
{
//接收到的数据
NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", msg);
}
//3、发送数据
- (void)sendMsg:(NSString *)msg
{
NSData *data = [msg dataUsingEncoding:NSUTF8StringEncoding];
[_sendTextUdpSocket sendData:data toHost:HOST port:PORT withTimeout:-1 tag:0x100];
}