用于与TCP套接字通话的Cocoa-Touch框架?

时间:2009-04-11 15:02:45

标签: iphone objective-c cocoa-touch

我在服务器上运行守护程序,该服务器锁定在TCP / IP端口上。我正在寻找是否有任何支持iPhone / Cocoa-touch框架,它提供了一个很好的OO包装器,可以通过IP套接字与守护进程通话。我需要能够以命令交互式地查询守护进程并检索信息。

如果没有任何OO包装器用于此类任务,那么下一个最好的选择是什么?

6 个答案:

答案 0 :(得分:15)

答案 1 :(得分:13)

以下是我之前提到的AsyncSocket代码中的一些示例代码,我将其修改为一个名为SocketCommunicationManager的类。

有几点需要注意:

  • 我们的消息用换行符(\ n)分隔,所以当从套接字读取数据时,我必须确保使用AsyncSocket类中的正常常量(在我们的例子中为LFData)。 AsyncSocket还提供CRLFData,CRData和ZeroData作为预定义的消息分隔符。
  • 我设置了SocketCommunicationManager,以便在我收到并执行前一个消息后始终等待收到的消息。为此,我使用了(void)readDataToData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag方法。此方法将一直等到数据写入套接字,读取到指定的分隔符,然后调用委托方法(void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag;
  • SocketCommunicationManager使用NSNotificationCenter发布从套接字接收的任何消息。这些消息被命名为kNotification,并使用kNotificationMessage密钥将消息放入userInfo字典中。
  • 从套接字读取的所有内容都包含在NSData对象中,因此您必须在收到数据后对其进行解码。

以下是代码:

#import <Foundation/Foundation.h>

extern NSString * const kNotification;
extern NSString * const kNotificationMessage;

@class AsyncSocket;

@interface SocketCommunicationManager : NSObject {
    AsyncSocket *socket;
    BOOL isRunning;
    NSNotificationCenter* notificationCenter;
}

@property (readwrite, assign) BOOL isRunning;

- (void)connectToHost:(NSString *)hostName onPort:(int)port;
- (void)sendMessage:(NSString *)message;
- (void)disconnect;

@end


#import "SocketCommunicationManager.h"
#import "AsyncSocket.h"

NSString * const kNotification = @"kNotification";
NSString * const kNotificationMessage = @"kNotificationMessage";

@implementation SocketCommunicationManager

@synthesize isRunning;

- (id) init {
    if (!(self = [super init]))
        return nil;

    socket = [[AsyncSocket alloc] initWithDelegate:self];
    [self setIsRunning:NO];
    notificationCenter = [NSNotificationCenter defaultCenter];

    return self;
}

- (void)connectToHost:(NSString *)hostName onPort:(int)port {
    if (![self isRunning]) {
        if (port < 0 || port > 65535)
            port = 0;

        NSError *error = nil;
        if (![socket connectToHost:hostName onPort:port error:&error]) {
            NSLog(@"Error connecting to server: %@", error);
            return;
        }

        [self setIsRunning:YES];
    } else {
        [socket disconnect];
        [self setIsRunning:false];
    }
}

- (void)disconnect {
    [socket disconnect];
}

- (void)dealloc {
    [super dealloc];
    [socket disconnect];
    [socket dealloc];
}

- (void)sendMessage:(NSString *)message {
    NSString *terminatedMessage = [message stringByAppendingString:@"\r\n"];
    NSData *terminatedMessageData = [terminatedMessage dataUsingEncoding:NSASCIIStringEncoding];
    [socket writeData:terminatedMessageData withTimeout:-1 tag:0];
}

#pragma mark AsyncSocket Delegate

- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port {
    NSLog(@"Connected to server %@:%hu", host, port);
    [sock readDataToData:[AsyncSocket LFData] withTimeout:-1 tag:0];
}

- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
    NSData *truncatedData = [data subdataWithRange:NSMakeRange(0, [data length] - 1)];
    NSString *message = [[[NSString alloc] initWithData:truncatedData encoding:NSASCIIStringEncoding] autorelease];

    if (message)
        NSLog(@"%@", message);
    else
        NSLog(@"Error converting received data into UTF-8 String");

    NSDictionary *userInfo = [NSDictionary dictionaryWithObject:message forKey:kNotificationMessage];
    [notificationCenter postNotificationName:kNotification object:self userInfo:userInfo];

    [sock readDataToData:[AsyncSocket LFData] withTimeout:-1 tag:0];
}

- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag {
    [sock readDataToData:[AsyncSocket LFData] withTimeout:-1 tag:0];
}

- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err {
    NSLog(@"Client Disconnected: %@:%hu", [sock connectedHost], [sock connectedPort]);
}


@end

答案 2 :(得分:6)

粗略地说,你可以上堆:

  • BSD套接字
  • CFSocket
  • CFReadStream / CFWriteStream / NSInputStream / NSOutputStream
  • CFHTTPStream
  • NSURLConnection的

听起来像你想要CFSocket,或者可能是CFStream。

答案 3 :(得分:2)

您是否查看了Cocoa-Touch的BSD Sockets中的networking guide

答案 4 :(得分:1)

正如Genericrich所指出的那样,Cocoa Async Socket框架是可行的方法。这已经存在了一段时间,并且看到了很多用途。 http://code.google.com/p/cocoaasyncsocket/

答案 5 :(得分:0)

正如Genericrich所指出的,AsyncSocket类对于处理套接字非常有用。 http://code.google.com/p/cocoaasyncsocket/