AsyncSocket对我不起作用

时间:2012-10-13 17:48:06

标签: objective-c cocoa asyncsocket

我首先要说的是,在问到这里之前我到处查找并搜索过 我正在尝试为iphone编写一个简单的应用程序,只需通过telnet连接到IP和端口, 我尝试了所有我对obj-c的新手(在java中花了我四分钟), 我不想使用线程,但我听说asyncsoket非常好..我不知道为什么,但是当我尝试时:

AsyncSocket * socket = [[AsyncSocket alloc] initwithDelegate:self];
[socket connectToHost:@"localhost" onPort:444 error:&err]

(这是一个有效的服务器) 它只是没有连接......

我所需要的只是连接到套接字写入和读取数据...
有没有我可以用作基础的简单代码示例(没有线程,没有runloop)?

1 个答案:

答案 0 :(得分:0)

ConnectDelegate.h

#import <Cocoa/Cocoa.h>
#import "AsyncSocket.h"

@class AsyncSocket;
@interface ConnectDelegate: NSObject {
    AsyncSocket *connectSocket;
}
- (void)connect;

@end

ConnectDelegate.m

#import "ConnectDelegate.h"
#import "AsyncSocket.h"

@implementation ConnectDelegate

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

- (void)connect
{
    connectSocket  = [[AsyncSocket alloc] initWithDelegate:self];
    connectSocket.delegate = self;

    NSError *error = nil;
    if (![connectSocket connectToHost:@"192.168.1.103" onPort:4000 error:&error]) {
        NSLog(@"Error starting client: %@", error);
        return;
    }
}

- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port{
    NSLog(@"connected to server");
}
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
    // some relevant code goes here
}
- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag{
}
@end

的main.m

int main(int const argc, char * const argv[] ) {
    ConnectDelegate *SocketConnection = [[ConnectDelegate alloc] init];
    [SocketConnection connect];

    // Run runloop
    [[NSRunLoop currentRunLoop] run];

return 0
}