当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《用于与TCP套接字通话的Cocoa-Touch框架?》经验,为你挑选了3个好方法。

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

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



1> Genericrich..:

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

这就是你想要的.


@Richards不,它仍然在https://github.com/robbiehanson/CocoaAsyncSocket上积极维护

2> Michael Fey..:

以下是我之前提到的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 

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



3> Mike Abdulla..:

粗略地说,你可以上升到堆栈:

BSD插座

CFSocket

CFReadStream/CFWriteStream/NSInputStream/NSOutputStream

CFHTTPStream

NSURLConnection的

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

推荐阅读
mobiledu2402851373
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有