iOS开发一般都使用第三方库CocoaAsyncSocket.
使用CocoaPods安装,在Podfile中添加下行:
pod 'CocoaAsyncSocket'
引入udpSocket
#import "GCDAsyncUdpSocket.h"
创建udpSocket
_udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_global_queue(0, 0)];
设置端口并发送
NSString *host = @"192.168.1.255";
NSTimeInterval timeout = 2000;
NSString *request = @"whereareyou\r\n";
NSData *data = [NSData dataWithData:[request dataUsingEncoding:NSASCIIStringEncoding]];
UInt16 port = 17888;
[_udpSocket sendData:data toHost:host port:port withTimeout:timeout tag:200];
这里的host对接受服务器返回的消息有影响,如果接收不到服务器回复的信息时可以改成255.255.255.255。
接收消息
//开启接收数据
[_udpSocket beginReceiving:&error];