简体   繁体   English

套接字的Objective-C NSMutableArray?

[英]Objective-C NSMutableArray of sockets?

I want to store a couple of sockets in an ArrayList/NSMutableArray, but the sockets are of type int and NSMutableArray only accepts objects (id). 我想在ArrayList / NSMutableArray中存储几个套接字,但是套接字的类型为int,而NSMutableArray仅接受对象(id)。 Is there another data type that I can use as a container for sockets? 是否有我可以用作套接字容器的另一种数据类型? I am not sure how many entries I will have, so I would like the data container to be like an ArrayList. 我不确定会有多少个条目,因此我希望数据容器像一个ArrayList。

Thanks! 谢谢!

EDIT: I've tried to send the socket as an NSNumber, but it did not work and caused XCode to crash when I tried to send a message using the socket. 编辑:我尝试将套接字作为NSNumber发送,但是当我尝试使用套接字发送消息时,它不起作用并导致XCode崩溃。

You should wrap up your file descriptors in NSFileHandle instances, these will play nice inside collection objects such as NSArray and are designed to wrap around file descriptors such as sockets. 您应该将文件描述符包装在NSFileHandle实例中,它们将在NSArray等集合对象中发挥NSArray ,并设计为用于包装套接字等文件描述符。 They also allow you to use standard Foundation types such as NSData in conjunction with your communication. 它们还允许您将标准Foundation类型(例如NSData )与您的通信一起使用。

int s = socket(AF_INET, SOCK_STREAM, 0);

if (s != -1)
{
    // bind or connect to address

    NSFileHandle *mySock = [[NSFileHandle alloc] initWithFileDescriptor:s closeOnDealloc:YES];

    [myMutableArray addObject:mySock];
}

Note that NSFileHandle also provides convenience methods for accepting connections asynchronously, as well as asynchronous I/O. 请注意, NSFileHandle还提供了方便的方法来异步接受连接以及异步I / O。 You can get the original file descriptor back by using the fileDescriptor method. 您可以使用fileDescriptor方法获得原始文件描述符。

You can wrap your int in an NSNumber like: 您可以将int包装在NSNumber中,如下所示:

NSNumber *socket = [NSNumber numberWithInt:socketInt];
[myArray addObject:socket];
NSNumber *getSocket = [myArray objectAtIndex:0];
int getSocketInt = [getSocket intValue];

More here 这里更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM