// Copyright (C) 2016 即时通讯网(52im.net)- 即时通讯开发者社区.
// All rights reserved.
// Created by JackJiang on 16/06/22.
#import "LocalUDPSocketProvider.h"
#import "GCDAsyncUdpSocket.h"
#import "ConfigEntity.h"
#import "CompletionDefine.h"
@interface LocalUDPSocketProvider ()
@property (nonatomic, retain) GCDAsyncUdpSocket *localUDPSocket;
@property (nonatomic, copy) ConnectionCompletion connectionCompletionOnce_;
@end
@implementation LocalUDPSocketProvider
// 本类的单例对象
static LocalUDPSocketProvider *instance = nil;
+ (LocalUDPSocketProvider *)sharedInstance
{
if (instance == nil)
instance = [[super allocWithZone:NULL] init];
return instance;
}
- (GCDAsyncUdpSocket *)initialLocalUDPSocket
{
NSLog(@"【IMCORE】new GCDAsyncUdpSocket中...");
// ** Setup our socket.
self.localUDPSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
// ** START udp socket
// 本地绑定端口合法性检查
int port = [ConfigEntity getLocalUdpSendAndListeningPort];
if (port < 0 || port > 65535)
port = 0;
NSError *error = nil;
// 绑定到指定端口(以便收发数据)
if (![self.localUDPSocket bindToPort:port error:&error])
{
NSLog(@"【IMCORE】localUDPSocket创建时出错,原因是 bindToPort: %@", error);
return nil;
}
// 开启收数据处理
if (![self.localUDPSocket beginReceiving:&error])
{
NSLog(@"【IMCORE】localUDPSocket创建时出错,原因是 beginReceiving: %@", error);
return nil;
}
NSLog(@"【IMCORE】localUDPSocket创建已成功完成.");
return self.localUDPSocket;
}
。。。。。。
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
fromAddress:(NSData *)address
withFilterContext:(id)filterContext
{
NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (msg)
NSLog(@"【UDP_SOCKET】【NOTE】>>>>>> 收到服务端的消息: %@", msg);
else
{
NSString *host = nil;
uint16_t port = 0;
[GCDAsyncUdpSocket getHost:&host port:&port fromAddress:address];
NSLog(@"【UDP_SOCKET】RECV: Unknown message from: %@:%hu", host, port);
}
}
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didConnectToAddress:(NSData *)address
{
NSLog(@"【UDP_SOCKET】成收到的了UDP的connect反馈, isCOnnected?%d", [sock isConnected]);
// 连接结果回调
if(self.connectionCompletionOnce_ != nil)
self.connectionCompletionOnce_(YES);
}
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didNotConnect:(NSError *)error
{
NSLog(@"【UDP_SOCKET】成收到的了UDP的connect反馈,但连接没有成功, isCOnnected?%d", [sock isConnected]);
// 连接结果回调
if(self.connectionCompletionOnce_ != nil)
self.connectionCompletionOnce_(NO);
}
@end