iPad 與局域網打印機 Socket 通信:集成 AsyncSocket 庫,連接打印機 IP/端口,發送 UTF-8 編碼文本數據。
// .h
#import
#import "AsyncSocket.h"
@interface ViewController : UIViewController {
AsyncSocket *asyncSocket;
}
@end
// .m
- (void)viewDidLoad {
[super viewDidLoad];
asyncSocket = [[AsyncSocket alloc] initWithDelegate:self];
[asyncSocket setRunLoopModes:@[NSRunLoopCommonModes]];
}
- (IBAction)printAction:(id)sender {
NSError *err = nil;
if (![asyncSocket connectToHost:@"192.168.1.105" onPort:18011 error:&err]) {
NSLog(@"Connect failed: %@", err);
return;
}
// 連接成功後 delegate 會回調 onSocket:didConnectToHost:port:
}
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port {
NSLog(@"Connected to %@:%hu", host, port);
NSString *printText = @"Socket測試成功!!!!";
NSData *data = [printText dataUsingEncoding:NSUTF8StringEncoding];
[sock writeData:data withTimeout:-1 tag:0];
[sock readDataWithTimeout:1 tag:0]; // 可選:讀取回應
}
- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag {
NSLog(@"Data sent");
}
- (void)onSocketDidDisconnect:(AsyncSocket *)sock {
NSLog(@"Disconnected");
}
AsyncSocket 異步非阻塞,需實現 AsyncSocketDelegate 回調。setRunLoopModes 確保在常見 RunLoop 模式下接收事件。AsyncSocket 讓 iOS Socket 通信輕鬆可靠,打印機集成不再難。