我正在尝试向服务器发送消息并使用我的iPhone接收回复。我可以使用:
连接到服务器telnet 123.123.123.1 6000
Trying 123.123.123.1...
Connected to 123.123.123.1.
Escape character is '^]'.
?VERSION
OK
VERSION=PROTOCOL: 1.1.0
?VERSION是我的问题
确定收到并理解了问题
VERSION =是来自服务器的响应
所以我试图用xcode做同样的事情
所以我在viewDidLoad
中有这个dispatch_queue_t mainQueue = dispatch_get_main_queue();
asyncSocket = [[GCDAsyncSocket alloc]initWithDelegate:self delegateQueue:mainQueue];
asyncSocket.delegate = self;
NSString *host = @"123.123.123.1";
uint16_t port = 6000;
NSLog(@"Connecting to \"%@\" on port %hu...", host, port);
NSError *error = nil;
if (![asyncSocket connectToHost:host onPort:port withTimeout:5.0 error:&error])
{
NSLog(@"Error connecting: %@", error);
}
else
{
NSLog(@"Connecting...");
}
我有以下代码显示已连接
-(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:
(UInt16)port
{
NSLog(@"socket:%p didConnectToHost:%@ port:%hu", sock, host, port);
// We're just going to send a test string to the server.
NSString *myStr = @"?VERSION";
NSData *myData2 = [myStr dataUsingEncoding:NSUTF8StringEncoding];
[asyncSocket writeData:myData2 withTimeout:-1 tag:0];
}
以下显示它写了
-(void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag{
NSLog(@"WRITING");
[asyncSocket readDataToData:[GCDAsyncSocket LFData] withTimeout:-1 tag:0];
}
可悲的是,这永远不会被称为
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
NSString *tempString = [[NSString alloc]initWithData:data
encoding: NSUTF8StringEncoding];
}
我迷路了,真的需要一些帮助
答案 0 :(得分:3)
这是因为你说同时写和读。首先致电[asyncSocket writeData:myData2 withTimeout:-1 tag:0];
并在didWriteDataWithTag
致电[asyncSocket readDataToData:[GCDAsyncSocket LFData] withTimeout:-1 tag:0];
。你在一个线程 - dispatch_get_main_queue()
- 它不能同时做两件事。