GCDTelnetServer 是 iOS 和 OS X 应用程序的嵌入式 Telnet 服务器。
特性
NSMutableString
要求
下载或检出 GCDTelnetServer 的最新发行版,然后将 "GCDTelnetServer" 和 "GCDNetworking/GCDNetworking" 子文件夹添加到您的 Xcode 项目中。
#import "GCDTelnetServer.h"
GCDTCPServer* server = [[GCDTelnetServer alloc] initWithPort:2323 startHandler:^NSString*(GCDTelnetConnection* connection) {
// Return welcome message
return [NSString stringWithFormat:@"You are connected using \"%@\"\n", connection.terminalType];
} lineHandler:^NSString*(GCDTelnetConnection* connection, NSString* line) {
// Simply echo back the received line but you could do anything here
return [line stringByAppendingString:@"\n"];
}];
[server start];
然后,在您的 Mac 上启动终端,简单地输入 telnet YOUR_COMPUTER_OR_IPHONE_IP_ADDRESS 2323
,你就会与您的应用进行“实时”通信。
GCDTelnetServer 有一个全面的定制 API,请确保查阅 GCDTelnetConnection.h。
GCDTelnetServer 最有趣的用途是在设备上运行应用程序时执行命令,例如,查询内部状态,在应用在后台时触发操作等...
此示例代码展示了如何实现带有更多信息(和 ANSI 颜色!)的欢迎消息,并支持 3 个命令(quit
、crash
和接受一些参数的 setwcolor
)
#import "GCDTelnetServer.h"
#import "NSMutableString+ANSI.h"
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {
GCDTCPServer* server = [[GCDTelnetServer alloc] initWithPort:2323 startHandler:^NSString*(GCDTelnetConnection* connection) {
UIDevice* device = [UIDevice currentDevice];
NSMutableString* welcome = [[NSMutableString alloc] init];
[welcome appendANSIStringWithColor:kANSIColor_Green bold:NO format:@"You are connected from %@ using \"%@\"\n", connection.remoteIPAddress, connection.terminalType];
[welcome appendANSIStringWithColor:kANSIColor_Green bold:NO format:@"Current device is %@ running %@ %@\n", device.model, device.systemName, device.systemVersion];
return welcome;
} commandHandler:^NSString*(GCDTelnetConnection* connection, NSString* command, NSArray* arguments) {
if ([command isEqualToString:@"quit"]) {
[connection close];
return nil;
} else if ([command isEqualToString:@"crash"]) {
abort();
} else if ([command isEqualToString:@"setwcolor"]) {
if (arguments.count == 3) {
dispatch_async(dispatch_get_main_queue(), ^{
_window.backgroundColor = [UIColor colorWithRed:[arguments[0] doubleValue] green:[arguments[1] doubleValue] blue:[arguments[2] doubleValue] alpha:1.0];
});
return @"OK\n";
}
return @"Usage: setwcolor red green blue\n";
}
NSMutableString* error = [[NSMutableString alloc] init];
[error appendANSIStringWithColor:kANSIColor_Red bold:YES format:@"UNKNOWN COMMAND = %@ (%@)\n", command, [arguments componentsJoinedByString:@", "]];
return error;
}];
[server start]; // TODO: Handle error
return YES;
}
以下是示例会话
$ telnet localhost 2323
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
You are connected from 127.0.0.1 using "XTERM-256COLOR"
Current device is iPad Simulator running iPhone OS 8.1
> test
UNKNOWN COMMAND = test ()
> setwcolor
Usage: setwcolor red green blue
> setwcolor 1 0 0
OK
> quitConnection closed by foreign host.