我正在尝试连接到一个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"
但是当我在终端中键入该命令时,服务器根本没有响应并按预期完成其工作。
答案 0 :(得分:1)
发现我唯一错误的是没有用\ r结束我的消息!我读到你需要以\ n结尾,但\ r \ n是为我做的。