iOS -Socket 开发基础(UDP)
2016-03-16 本文已影响1739人
小兵快跑
run.jpg
前言
什么是UDP协议广播机制?
举一个例, 例如在一群人群中,一个人要找张三,于是你向人群里大喊一声(广播):“谁是张三”
如果它是张三,它就会回应你,在网络中也是一样的。
UDP广播机制的应用场景:
若干个客户端,在局域网内(不知道IP的情况下) 需要在很多设备里需找特有的设备,比如服务器,抑或是某个打印机,传真机等。
假设我现在准备将服务器装在永不断电的iPhone上。
若干个客户端iPhone 一激活,就要来向所有设备广播,谁是服务器,是服务器的话,请把IP地址告诉我。然后我就去连接,然后进入长连接,后台接受消息。
客服端发送集成:
#import "ViewController.h"
#import "AsyncUdpSocket.h"
#define PORT 5555
@interface ViewController ()
{
/** 发送*/
AsyncUdpSocket *_sendSocket;
}
@property (weak, nonatomic) IBOutlet UITextField *IPField;
@property (weak, nonatomic) IBOutlet UITextField *sendField;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)sendMSG:(id)sender {
_sendSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
[_sendSocket bindToPort:PORT error:nil];
NSData *data = [self.sendField.text dataUsingEncoding:NSUTF8StringEncoding];
BOOL res = [_sendSocket sendData:data toHost:self.IPField.text port:PORT withTimeout:30 tag:0];
if (!res) {
TTAlertNoTitle(@"发送失败");
}
}
#pragma mark -
#pragma mark UDP Delegate Methods
//无法发送时,返回的异常提示信息
- (void)onUdpSocket:(AsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error
{
TTAlertNoTitle([error description]);
}
void TTAlertNoTitle(NSString* message) {
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示"
message:message
delegate:nil
cancelButtonTitle:@"取消"
otherButtonTitles:nil];
[alert show];
}
服务器接收集成:
#import "ViewController.h"
#import "AsyncUdpSocket.h"
#define PORT 5555
@interface ViewController ()
{
/** 接收*/
AsyncUdpSocket *_recvSocket;
}
@property (weak, nonatomic) IBOutlet UITextView *MSGView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_recvSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
[_recvSocket bindToPort:PORT error:nil];
[_recvSocket receiveWithTimeout:-1 tag:0];
}
#pragma mark -
#pragma mark UDP Delegate Methods
- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port
{
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
self.MSGView.text = str;
NSLog(@"host---->%@ port--%i str----%@",host,port,str);
return YES;
}
//无法接收时,返回异常提示信息
- (void)onUdpSocket:(AsyncUdpSocket *)sock didNotReceiveDataWithTag:(long)tag dueToError:(NSError *)error
{
TTAlertNoTitle([error description]);
}
void TTAlertNoTitle(NSString* message) {
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示"
message:message
delegate:nil
cancelButtonTitle:@"取消"
otherButtonTitles:nil];
[alert show];
}