iPhone UDP监听器/服务器 - 没有获取数据回调
我遇到一个问题,无法从 CF 套接字获取数据回调。我的应用程序允许用户设置最多 4 个数据传输通道(我将其称为“试验”,因为我不知道通道是否意味着特定的内容。)到目前为止,我仅在模拟器中进行测试,并且我只使用 UDP。对于每次试验,我都会初始化套接字驱动程序类的一个新实例(在模拟器情况下称为 SimSocket,分别初始化为发送或接收的发布者或订阅者),发送/接收相对少量的数据,然后关闭套接字并释放SimSocket。然后我再进行一次试验,依此类推。
失败的原因如下:我将试验 #0 设置为接收器,然后设置试验 #1 将数据发送到 127.0.0.1。我启动接收器,然后启动发送器,数据传输工作正常。我可以一遍又一遍地重复这个,没有问题。然后,在不更改任何 IP 或端口地址、数据包大小或数据包速率的情况下,我只运行试验 1,因此数据会发送到以太网或其他地方。发生这种情况时,我在控制台输出中没有看到任何问题。接下来,我再次启动接收器,试验 0,然后运行发送器,试验 1。但现在我从未看到任何数据回调,并且试验 0 从未获得任何要处理的数据。我的问题是,为什么试验 0 在该序列之后无法接收数据?
一些支持信息......我在 Mac 上运行 Wireshark 查看环回接口。即使在试验 0 失败的运行中,我仍然可以在 Wireshark 中看到我期望看到的 UDP 数据报。对于上述整个序列,我在控制台输出中看到套接字始终正确打开和关闭(除了最后一次尝试 0 失败 - 当然它永远不会到达关闭点)。所有接收代码都在主线程上执行。当我发送一组数据时,我在一个单独的线程上执行此操作,但无论工作正常还是不工作,情况都是一样的。当以 2 Kbps 的速度发送 10 个 50 字节的原始数据“数据包”时,我可能会遇到此故障。
以下是我的 SimSocket 实现文件的相关部分。我感谢您能提供的任何帮助。谢谢。
#import "SimSocket.h"
void simReceivedDataCallback(CFSocketRef s, CFSocketCallBackType type, CFDataRef address, const void *data, void *info) {
// NOTE: I don't know if I'm accessing the address argument properly here, or if it contains useful information!
NSLog(@"SimSocket: simReceivedDataCallback function entry. Socket=%d, address=%s, port=%d", CFSocketGetNative(s), inet_ntoa(((struct sockaddr_in *)address)->sin_addr), htons(((struct sockaddr_in *)address)->sin_port));
// send data to SimSocket delegate here
}
@implementation SimSocket
@synthesize readyToUse, delegate, errors;
- (id)initWithType:(SimSocketConnection)connectionType1 host:(NSString *)host1 port:(int)port1 {
if (self = [super init]) {
hostStr = host1;
port = port1;
isPublish = YES;
connectionType = connectionType1;
readyToUse = NO;
int sockType = (connectionType == SimSocketConnectionTcp) ? SOCK_STREAM : SOCK_DGRAM;
sockfd = socket(AF_INET, sockType, 0);
if (sockfd == -1) {
NSLog(@"SimSocket:initWithType: Error with socket() - %s", strerror(errno));
return self;
}
memset((void *)&address_in, 0, sizeof(address_in));
address_in.sin_family = AF_INET;
address_in.sin_port = htons(port);
address_in.sin_addr.s_addr = inet_addr([hostStr UTF8String]);
addressData = [NSData dataWithBytes:&address_in length:sizeof(address_in)];
readyToUse = YES;
return self;
}
else {
return nil;
}
}
- (id)initPublishWithType:(SimSocketConnection)connectionType1 host:(NSString *)host1 port:(int)port1 {
if ([self initWithType:connectionType1 host:host1 port:port1]) {
readyToUse = NO;
NSLog(@"SimSocket:initPublishWithType: Successfully created BSD socket - %d", sockfd);
cfsocket = CFSocketCreateWithNative(NULL, sockfd, kCFSocketConnectCallBack, simCallback, NULL);
if (cfsocket == NULL) {
NSLog(@"SimSocket:initPublishWithType: Error with CFSocketCreateWithNative()");
return self;
}
readyToUse = YES;
}
return self;
}
- (id)initSubscribeWithType:(SimSocketConnection)connectionType1 host:(NSString *)host1 port:(int)port1 delegate:(id <SimSocketEvents>)delegate1 {
NSLog(@"SimSocket:initSubscribeWithType: starting initialization with delegate %@", delegate1);
if ([self initWithType:connectionType1 host:host1 port:port1]) {
readyToUse = NO;
NSLog(@"SimSocket:initSubscribeWithType: Successfully created BSD socket - %d", sockfd);
delegate = delegate1;
address_in.sin_addr.s_addr = htonl(INADDR_ANY);
addressData = [NSData dataWithBytes:&address_in length:sizeof(address_in)];
int yes = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
NSLog(@"SimSocket:initSubscribeWithType: Error with setsockopt() with SO_REUSEADDR - %s", strerror(errno));
}
if (bind(sockfd, (struct sockaddr*) &address_in, sizeof(address_in)) == -1) {
NSLog(@"SimSocket:initSubscribeWithType: Error with bind() - %s", strerror(errno));
errors = [NSString stringWithFormat:@"Bind Failed - %s. Try using a Different Port number.", strerror(errno)];
close (sockfd);
return self;
}
CFSocketContext context = { 0, (void *)self, NULL, NULL, NULL };
// TCP
if (connectionType == SimSocketConnectionTcp) {
if (listen(sockfd, 10) == -1) {
NSLog(@"SimSocket:initSubscribeWithType: Error with listen() - %s", strerror(errno));
return self;
}
cfsocket = CFSocketCreateWithNative(NULL, sockfd, kCFSocketAcceptCallBack, simAcceptCallback, &context);
}
// UDP
else if (connectionType == SimSocketConnectionUdp) {
cfsocket = CFSocketCreateWithNative(NULL, sockfd, kCFSocketDataCallBack, simReceivedDataCallback, &context);
}
if (cfsocket == NULL) {
NSLog(@"SimSocket:initSubscribeWithType: Error with CFSocketCreateWithNative()");
return self;
}
CFRunLoopSourceRef source = CFSocketCreateRunLoopSource(NULL, cfsocket, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
CFRelease(source);
NSLog(@"SimSocket:initSubscribeWithType: Current run loop = %x. Main thread run loop = %x.", CFRunLoopGetCurrent(), CFRunLoopGetMain());
readyToUse = YES;
NSLog(@"SimSocket:initSubscribeWithType: Completed socket initialization successfully.");
}
return self;
}
- (void)dealloc {
if (cfsocket) CFRelease(cfsocket);
if (sockfd != -1) close(sockfd);
[errors release];
[super dealloc];
}
-(void)shutdown
{
NSLog(@"SimSocket: shutdown: Am shutting down the socket. sockfd = %d", sockfd);
if (cfsocket) CFRelease(cfsocket);
if (sockfd != -1) close(sockfd);
}
- (void)sendBytes:(const void *)bytes length:(int)length {
if (!readyToUse) {
NSLog(@"SimSocket:sendBytes: socket not ready to use for sending");
return;
}
int bytesSent;
if (connectionType == SimSocketConnectionTcp) {
bytesSent = send(sockfd, bytes, length, 0);
}
else {
bytesSent = sendto(sockfd, bytes, length, 0, (struct sockaddr *)&address_in, sizeof(address_in));
}
if (bytesSent < 0) {
NSLog(@"SimSocket:sendBytes: Oops, error- %s. No bytes sent.", strerror(errno));
}
else if (bytesSent < length) {
NSLog(@"SimSocket:sendBytes: Oops, error- %s. Only %i sent out of %i", strerror(errno), bytesSent, length);
}
else {
NSLog(@"SimSocket:sendBytes: Successfully sent the packet (%d bytes) to %s", length, inet_ntoa(address_in.sin_addr));
}
NSLog(@"SimSocket:sendBytes: Current run loop = %x. Main thread run loop = %x.", CFRunLoopGetCurrent(), CFRunLoopGetMain());
}
@end
I have a problem where I am not getting a data callback from a CF socket. My application allows the user to set up up to 4 channels of data transfer (I'll call them "trials", since I don't know if channel means something specific.) So far, I am only testing in the simulator, and am only working with UDP. For each trial, I initialize a new instance of my socket driver class (called SimSocket for the simulator case, initialized as publisher or subscriber for send or receive respectively), send/receive a relatively small amount of data, then close the socket and release SimSocket. Then I do another trial, etc, etc.
Here is how it fails: I set up trial #0 as a receiver, then set up trial #1 to send data to 127.0.0.1. I start the receiver, then the sender, and data transfer works fine. I can repeat this over and over, no problems. Then, without changing any IP or port addresses or packet sizes or packet rates, I run just trial 1, so the data goes out to the ether or somewhere. I don't see any issues in my console output when this happens. Next I start the receiver again, trial 0, then run the sender, trial 1. But now I never see any data callbacks, and trial 0 never gets any data to process. My question is, why does trial 0 fail to receive data after that sequence?
Some supporting info.... I run Wireshark on the Mac looking at the loopback interface. Even on the run where trial 0 fails, I still see the UDP datagrams in Wireshark that I would expect to see. For the entire sequence described above, I see in my console output that sockets are always being opened and closed properly (except the last trial 0 that fails - it never gets to the point of closing of course). All receive code is executing on the main thread. When I send a set of data, I do that on a separate thread, but that is the same when things work and when they don't. I can get this failure when sending 10 50-byte 'packets' of raw data at 2 Kbps.
Below are pertinent parts of my SimSocket implementation file. I appreciate any help you can provide. Thanks.
#import "SimSocket.h"
void simReceivedDataCallback(CFSocketRef s, CFSocketCallBackType type, CFDataRef address, const void *data, void *info) {
// NOTE: I don't know if I'm accessing the address argument properly here, or if it contains useful information!
NSLog(@"SimSocket: simReceivedDataCallback function entry. Socket=%d, address=%s, port=%d", CFSocketGetNative(s), inet_ntoa(((struct sockaddr_in *)address)->sin_addr), htons(((struct sockaddr_in *)address)->sin_port));
// send data to SimSocket delegate here
}
@implementation SimSocket
@synthesize readyToUse, delegate, errors;
- (id)initWithType:(SimSocketConnection)connectionType1 host:(NSString *)host1 port:(int)port1 {
if (self = [super init]) {
hostStr = host1;
port = port1;
isPublish = YES;
connectionType = connectionType1;
readyToUse = NO;
int sockType = (connectionType == SimSocketConnectionTcp) ? SOCK_STREAM : SOCK_DGRAM;
sockfd = socket(AF_INET, sockType, 0);
if (sockfd == -1) {
NSLog(@"SimSocket:initWithType: Error with socket() - %s", strerror(errno));
return self;
}
memset((void *)&address_in, 0, sizeof(address_in));
address_in.sin_family = AF_INET;
address_in.sin_port = htons(port);
address_in.sin_addr.s_addr = inet_addr([hostStr UTF8String]);
addressData = [NSData dataWithBytes:&address_in length:sizeof(address_in)];
readyToUse = YES;
return self;
}
else {
return nil;
}
}
- (id)initPublishWithType:(SimSocketConnection)connectionType1 host:(NSString *)host1 port:(int)port1 {
if ([self initWithType:connectionType1 host:host1 port:port1]) {
readyToUse = NO;
NSLog(@"SimSocket:initPublishWithType: Successfully created BSD socket - %d", sockfd);
cfsocket = CFSocketCreateWithNative(NULL, sockfd, kCFSocketConnectCallBack, simCallback, NULL);
if (cfsocket == NULL) {
NSLog(@"SimSocket:initPublishWithType: Error with CFSocketCreateWithNative()");
return self;
}
readyToUse = YES;
}
return self;
}
- (id)initSubscribeWithType:(SimSocketConnection)connectionType1 host:(NSString *)host1 port:(int)port1 delegate:(id <SimSocketEvents>)delegate1 {
NSLog(@"SimSocket:initSubscribeWithType: starting initialization with delegate %@", delegate1);
if ([self initWithType:connectionType1 host:host1 port:port1]) {
readyToUse = NO;
NSLog(@"SimSocket:initSubscribeWithType: Successfully created BSD socket - %d", sockfd);
delegate = delegate1;
address_in.sin_addr.s_addr = htonl(INADDR_ANY);
addressData = [NSData dataWithBytes:&address_in length:sizeof(address_in)];
int yes = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
NSLog(@"SimSocket:initSubscribeWithType: Error with setsockopt() with SO_REUSEADDR - %s", strerror(errno));
}
if (bind(sockfd, (struct sockaddr*) &address_in, sizeof(address_in)) == -1) {
NSLog(@"SimSocket:initSubscribeWithType: Error with bind() - %s", strerror(errno));
errors = [NSString stringWithFormat:@"Bind Failed - %s. Try using a Different Port number.", strerror(errno)];
close (sockfd);
return self;
}
CFSocketContext context = { 0, (void *)self, NULL, NULL, NULL };
// TCP
if (connectionType == SimSocketConnectionTcp) {
if (listen(sockfd, 10) == -1) {
NSLog(@"SimSocket:initSubscribeWithType: Error with listen() - %s", strerror(errno));
return self;
}
cfsocket = CFSocketCreateWithNative(NULL, sockfd, kCFSocketAcceptCallBack, simAcceptCallback, &context);
}
// UDP
else if (connectionType == SimSocketConnectionUdp) {
cfsocket = CFSocketCreateWithNative(NULL, sockfd, kCFSocketDataCallBack, simReceivedDataCallback, &context);
}
if (cfsocket == NULL) {
NSLog(@"SimSocket:initSubscribeWithType: Error with CFSocketCreateWithNative()");
return self;
}
CFRunLoopSourceRef source = CFSocketCreateRunLoopSource(NULL, cfsocket, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
CFRelease(source);
NSLog(@"SimSocket:initSubscribeWithType: Current run loop = %x. Main thread run loop = %x.", CFRunLoopGetCurrent(), CFRunLoopGetMain());
readyToUse = YES;
NSLog(@"SimSocket:initSubscribeWithType: Completed socket initialization successfully.");
}
return self;
}
- (void)dealloc {
if (cfsocket) CFRelease(cfsocket);
if (sockfd != -1) close(sockfd);
[errors release];
[super dealloc];
}
-(void)shutdown
{
NSLog(@"SimSocket: shutdown: Am shutting down the socket. sockfd = %d", sockfd);
if (cfsocket) CFRelease(cfsocket);
if (sockfd != -1) close(sockfd);
}
- (void)sendBytes:(const void *)bytes length:(int)length {
if (!readyToUse) {
NSLog(@"SimSocket:sendBytes: socket not ready to use for sending");
return;
}
int bytesSent;
if (connectionType == SimSocketConnectionTcp) {
bytesSent = send(sockfd, bytes, length, 0);
}
else {
bytesSent = sendto(sockfd, bytes, length, 0, (struct sockaddr *)&address_in, sizeof(address_in));
}
if (bytesSent < 0) {
NSLog(@"SimSocket:sendBytes: Oops, error- %s. No bytes sent.", strerror(errno));
}
else if (bytesSent < length) {
NSLog(@"SimSocket:sendBytes: Oops, error- %s. Only %i sent out of %i", strerror(errno), bytesSent, length);
}
else {
NSLog(@"SimSocket:sendBytes: Successfully sent the packet (%d bytes) to %s", length, inet_ntoa(address_in.sin_addr));
}
NSLog(@"SimSocket:sendBytes: Current run loop = %x. Main thread run loop = %x.", CFRunLoopGetCurrent(), CFRunLoopGetMain());
}
@end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
伙计们,看来我发现了问题。当关闭时,我只释放 CFSocket。遵循 UDPEcho 示例项目的指导,我将其替换为 3 个步骤:CFSocketInvalidate 调用、CFRelease 调用,然后将 CFSocket 引用设置为 NULL。现在似乎运行良好。
Folks, it looks like I found the problem. When shutting things down, I was only releasing the CFSocket. Following the lead of the UDPEcho sample project, I replaced this with 3 steps: a CFSocketInvalidate call, a CFRelease call, then set the CFSocket reference to NULL. It seems to be working fine now.