首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Cocoa-Touch框架用于与TCP套接字通信?

Cocoa-Touch框架用于与TCP套接字通信?
EN

Stack Overflow用户
提问于 2009-04-11 15:02:45
回答 6查看 11.7K关注 0票数 9

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

如果这样的任务没有任何面向对象的包装器,那么下一个最好的选择是什么?

EN

回答 6

Stack Overflow用户

发布于 2009-04-11 17:48:37

http://code.google.com/p/cocoaasyncsocket/

这就是你想要的。

票数 15
EN

Stack Overflow用户

发布于 2009-04-13 13:53:31

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

需要注意的几件事:

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

代码如下:

代码语言:javascript
复制
#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
票数 13
EN

Stack Overflow用户

发布于 2009-04-11 17:42:45

粗略地说,向上堆栈你有:

  • BSD sockets
  • CFSocket
  • CFReadStream/CFWriteStream/NSInputStream/NSOutputStream
  • CFHTTPStream
  • NSURLConnection

听起来您需要CFSocket,或者可能需要CFStream。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/740258

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档