[英]iOS UDP communication both ways
I'm making an iOS application that is supposed to communicate using the UDP protocol (the devices are connected to the same Wi-Fi network). 我正在制作一个应该使用UDP协议进行通信的iOS应用程序(这些设备已连接到同一Wi-Fi网络)。 I managed to create a socket, and send some data to the designated IP address:
我设法创建了一个套接字,并将一些数据发送到指定的IP地址:
const char *ip = "192.168.1.100";
- (void)initNetworkCommunication {
cfSocket = CFSocketCreate(kCFAllocatorDefault, AF_INET, SOCK_DGRAM, IPPROTO_UDP, 0, NULL, NULL);
if ( cfSocket == NULL) {
NSLog(@"CfSocketCreate failed");
}else{
if( cfSocket ) {
NSLog(@"Socket created ");
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_len = sizeof(addr);
addr.sin_family = AF_INET;
addr.sin_port = htons(1470); //port
inet_pton(AF_INET,ip, &addr.sin_addr); //ip adress
CFDataRef addrData = CFDataCreate(NULL, (const UInt8*)&addr, sizeof(addr));
CFSocketSetAddress (cfSocket, addrData);
char message []= "UDP test message";
CFDataRef Data = CFDataCreate(NULL, (const UInt8*)message, sizeof(message));
CFSocketSendData(cfSocket,addrData, Data, 0);
}
}
This works quite well i think, as the device gets the message. 我认为这非常有效,因为设备会收到消息。 The problem is I really have no idea where to start on listening for/receiving data.
问题是我真的不知道从哪里开始侦听/接收数据。 I've tried to search for some help, but sadly without any useful results.
我试图寻找一些帮助,但可惜没有任何有用的结果。 Most people are using external libraries, which i would like to avoid.
大多数人都在使用外部库,我想避免这种情况。 If anyone could give me some guidance in this topic, I'd be really thankful.
如果有人可以在这个主题上给我一些指导,我将非常感激。
I have searched some more this morning, and actually found what i was looking for in this topic: 今天早上我进行了更多搜索,实际上找到了我在该主题中正在寻找的内容:
UDP broadcast using CFSocket on IOS 在iOS上使用CFSocket进行UDP广播
Adding a callback to the socket, together with configuring a RunLoop works like a charm :) And if you want to get the data from the callback just use something like this: 向套接字添加回调,以及配置RunLoop就像一个超级魅力:)并且,如果您想从回调中获取数据,只需使用以下代码:
NSData * someData = (NSData*)data;
NSString * someString = [[NSString alloc] initWithData:someData encoding:NSASCIIStringEncoding];
Hope this helps someone. 希望这对某人有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.