ios oc socket组播包发送与接收
时间: 2023-08-18 20:08:37 浏览: 114
1. 发送组播包
在 iOS 中,可以使用 MulticastSocket 来发送组播包。以下是发送组播包的步骤:
1)创建 MulticastSocket 对象:
```objc
self.multicastSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
```
2)设置 MulticastSocket 的发送地址和端口:
```objc
NSString *host = @"224.0.0.1";
int port = 12345;
NSError *error = nil;
[self.multicastSocket enableBroadcast:YES error:&error];
[self.multicastSocket joinMulticastGroup:host error:&error];
[self.multicastSocket beginReceiving:&error];
```
3)发送组播包:
```objc
NSString *message = @"Hello, world!";
NSData *data = [message dataUsingEncoding:NSUTF8StringEncoding];
[self.multicastSocket sendData:data toHost:host port:port withTimeout:-1 tag:0];
```
2. 接收组播包
以下是接收组播包的步骤:
1)创建 MulticastSocket 对象:
```objc
self.multicastSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
```
2)设置 MulticastSocket 的接收地址和端口:
```objc
NSString *host = @"224.0.0.1";
int port = 12345;
NSError *error = nil;
[self.multicastSocket enableBroadcast:YES error:&error];
[self.multicastSocket joinMulticastGroup:host error:&error];
[self.multicastSocket beginReceiving:&error];
```
3)实现 GCDAsyncUdpSocketDelegate 的回调方法:
```objc
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(nullable id)filterContext {
NSString *message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Received message: %@", message);
}
```
这样就可以接收到发送到指定组播地址和端口的包了。
阅读全文