我正在尝试连接到telnet服务器(如果需要,可以通过AMX运行NetLinx)并向其发送一些命令,就像我打开Terminal并执行“ 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];
}
它似乎向服务器发送了某种消息,但格式可能错误。我的猜测是这是一个字符串格式化问题。我要在telnet中使用ASCII吗?如果我收到消息,则它会在发送命令时打印并粘贴到运行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"
但是,当我在终端中键入该命令时,服务器根本不响应,并按其应有的方式工作。
发现我做错的唯一一件事就是没有用\ r结束我的消息!我读到您需要以\ n结尾,但是\ r是为我做的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句