我正在尝试连接到 telnet 服务器(通过 AMX 运行 NetLinx,以防万一)并向它发送一些命令,就像我打开终端并执行“telnet(地址)”并开始输入命令一样。我可以接收消息,但无法使用从http://www.raywenderlich.com/3932/how-to-create-a-socket-based-iphone-app-and-server的教程中找到的代码发送消息:
- (void)sendMessage: (NSString*) message{ //called when the user interacts with UISwitches, is supposed to send message to server
NSData *data = [[NSData alloc] initWithData:[message dataUsingEncoding:NSASCIIStringEncoding]]; //is ASCIIStringEncoding what I want?
[outputStream write:[data bytes] maxLength:[data length]];
NSLog(@"Sent message to server: %@", message);
}
- (void)initNetworkCommunication { //called in viewDidLoad of the view controller
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"192.168.1.90", 23, &readStream, &writeStream); //192.168.1.90 is the server address, 23 is standard telnet port
inputStream = (__bridge NSInputStream *)readStream;
outputStream = (__bridge NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
}
它似乎向服务器发送某种消息,但格式可能不正确。我的猜测是这是一个字符串格式问题。ASCII 是我想用于 telnet 的吗?如果我接收它在发送命令时打印的消息并将其粘贴到运行 telnet 的终端中,则服务器会正常接收并处理命令。
这是我尝试发送的示例命令:SEND_STRING dvJAND,"'#AUX2=0',$0D"
另一个谜团是,读取输入流并打印,我在发送上述内容时看到了这一点:
2013-08-20 00:20:23.791 [7548:907] server said: S
2013-08-20 00:20:23.793 [7548:907] server said: END_STRING dvJAND,"'#AUX
2013-08-20 00:20:23.795 [7548:907] server said: 2=0',$0D"
但是当我在终端中键入该命令时,服务器根本没有响应并按其应有的方式工作。