2012-06-07 4 views
1

나는이 문제에 며칠 동안 고생하고 있으며 (위대한 사용자 @ SO의 도움으로) 해결책에 가까워지고있는 것처럼 보입니다. CocoaAsyncSocket 라이브러리를 사용하여 Windows 서버에 대한 TCP 소켓 연결을 만듭니다.라이브러리 (대리자) 메서드가 호출되지 않는 이유는 무엇입니까?

연결이 내 AppDelegate에에서 이루어지고

: (AsyncSocket *) 양말 didConnectToHost :

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    socket = [[AsyncSocket alloc] initWithDelegate:self]; 
    NSError *error = nil; 
    if (![socket connectToHost:@"199.5.83.63" onPort:11005 error:&error]) 
    { 
     NSLog(@"Error connecting: %@", error); 
    } 

    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease]; 
    // Override point for customization after application launch. 
    self.viewController = [[[tekMatrixViewController alloc] initWithNibName:@"tekMatrixViewController" bundle:nil] autorelease]; 
    self.window.rootViewController = self.viewController; 
    [self.window makeKeyAndVisible]; 
    return YES; 
} 

내가 (라이브러리의 일부)라고 onSocket 커넥트 방법을 (있는 NSString *) 호스트 포트 :(UINT16) 포트 : 나는 NSLOG의 출력을 볼 수

- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port 
{ 
    NSLog(@"connected :D"); 
} 

이 방법 를 호출되고 난이 성공적으로 연결하고있다. 로그 파일을 사용하여 Windows 시스템에서 성공적으로 연결되었음을 알 수 있습니다.

나는 또한 다른 대리자 메서드 뿐만 아니라 호출되는 것을 테스트 한

: 제가 테스트 한

- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err 
{ 
    NSLog(@"error - disconnecting"); 
    // start reconnecting procedure here... 
} 

willDisconnectWithError 방법은 시뮬레이터 내 응용 프로그램을 실행하고 그때부터 내 이더넷 코드의 플러그를 뽑아 작동하는지 내 휴대용 퍼스널 컴퓨터. 이 작업을 수행하면 출력에서 ​​"오류 연결 해제"문자열을 보았습니다.

그러나 큰 문제는 내 대리자 메서드 (다시 라이브러리에서)가 호출되지 않는다는 것입니다. 호출되지

위임 방법 :

- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag 
{ 
    NSData *strData = [data subdataWithRange:NSMakeRange(0, [data length])]; 
    NSString *msg = [[NSString alloc] initWithData:strData encoding:NSUTF8StringEncoding]; 
    if(msg) 
    { 
     NSLog(@"RX:%@",msg); 
    } 
    else 
    { 
     NSLog(@"Fail"); 
    }  
} 

내가 대리자 메서드의 작동 방식 내 지식과 이해 확신 해요,하지만 난 여전히 매우 그들이 호출하는 방법 따르지 않습니다. 더욱 복잡하고 혼란을 야기하기 위해 하나의 위임 메소드 (onSocket : didConnectToHost 포트 :)가 호출되었지만 다른 (onSocket : didReadData 태그 :)가 호출되지 않습니다. 불행히도이 문제는 제 1 단계에 불과하지만 다른 문제가 발생하기 전에이 문제를 해결해야합니다.

도움을 주시면 감사하겠습니다. 감사합니다 : D를 AsyncSocket.h 파일에서

+0

Windows 서버는 어떻게 구현됩니까? 일부 '서버'는 버퍼가 가득 찰 때까지 또는 CR & LF 또는 CR 문자를받을 때까지 데이터를 보내지 않기 때문에 묻습니다. 그래서 : 당신의 서버가 데이터를 보내고 있다는 것을 확신합니까? 언제든지 telneting으로 확인할 수 있습니다. –

+0

덧붙여서 위임 메서드가 어떻게 호출되는지 알고 싶으면 AsyncSocket.m의 소스 코드를 살펴보십시오. 3782 번에서 3785 행까지는 onSocket : didReadData : withTag :가 호출 된 방식을 정확하게 보여줍니다. – glorifiedHacker

+0

또 다른 옵션은 데이터가 UTF8 문자열이 아니라는 것입니다. 'NSLog ("수신 길이 : % d", [데이터 길이]);'if (msg)'앞에 추가하십시오. 어떤 결과가 있습니까? 물론 이것이 호출 될 때만 이해할 수 있습니다. –

답변

5

:

/** 
* Called when a socket has completed reading the requested data into memory. 
* Not called if there is an error. 
**/ 
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag; 

내 첫번째 추측은 오류가 있고 대리자 메서드가 호출되지 않는 이유는 점이다. 또한 오류 처리를위한 대리자 메서드를 구현 했습니까?

/** 
* In the event of an error, the socket is closed. 
* You may call "unreadData" during this call-back to get the last bit of data off the socket. 
* When connecting, this delegate method may be called 
* before"onSocket:didAcceptNewSocket:" or "onSocket:didConnectToHost:". 
**/ 
- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err; 

참고 : 오류없이 연결할 수 있기 때문에 오류가 발생하지 않고 읽을 수 있습니다. connectToHost:onPort:error:에 전달하는 오류 인수가 모든 오류 조건을 다루는 것은 아닙니다.

편집 : 소켓에서 "readData"메소드 중 하나를 호출하는 코드 부분을 게시 할 수 있습니까? 거기에서 간과되고있는 것이있을 수 있습니다. 예를 들어 소켓에 "readData"메시지를 보내지 않으면 위임 메서드가 호출되지 않는 이유가 설명됩니다.

편집 : onSocket:didReadData:withTag: 메서드는 소켓에서 다음 readData 메서드 중 하나를 호출 한 후에 만 ​​호출됩니다. 예 :

// The readData and writeData methods won't block (they are asynchronous). 
// 
// When a read is complete the onSocket:didReadData:withTag: delegate method is called. 
// When a write is complete the onSocket:didWriteDataWithTag: delegate method is called. 
// 
// You may optionally set a timeout for any read/write operation. (To not timeout, use a negative time interval.) 
// If a read/write opertion times out, the corresponding "onSocket:shouldTimeout..." delegate method 
// is called to optionally allow you to extend the timeout. 
// Upon a timeout, the "onSocket:willDisconnectWithError:" method is called, followed by "onSocketDidDisconnect". 
// 
// The tag is for your convenience. 
// You can use it as an array index, step number, state id, pointer, etc. 

/** 
* Reads the first available bytes that become available on the socket. 
* 
* If the timeout value is negative, the read operation will not use a timeout. 
**/ 
- (void)readDataWithTimeout:(NSTimeInterval)timeout tag:(long)tag; 
+0

예, willDisconnectWithError가 구현되었습니다. 시뮬레이터에서 앱을 실행할 때 랩톱에서 이더넷 코드를 뽑아 테스트했습니다. 필자가 구현 한 추가 위임 방법으로 원래 게시물을 업데이트합니다. 빠른 답장을 보내 주셔서 감사합니다! – Skizz

+0

모든 정직한면에서 didConnectToHost 및 didDisconnectWithError가 호출/호출되는 방법을 모르겠습니다. 내 didReadData 메소드가 호출되거나 호출되지 않으면 어떻게 호출/호출 할 것인가? – Skizz

+0

위의 대답을 AsyncSocket 헤더 파일의 자세한 내용으로 편집했습니다. 코드의 어딘가에서 다음과 같이 호출해야합니다. [socket readDataWithTimeout : 10 tag : 1234567890]; – glorifiedHacker

관련 문제