问题描述:我想要再ipad程序里面,用代码给打印机发送一段字符串,然后打印。
具体情况是这样的,现在想要用wifi连接到打印机,然后给打印机发送一个字符串去打印。但是问题是不知道如何连接打印机,也不知道如何给打印机发送消息。其中打印机和ipad在同一个局域网下,想用socket通过打印机的ip地址进行传送要打印的内容。
.h 里面
Objective C code
#import <UIKit/UIKit.h>
#import "AsyncSocket.h"
@interface ViewController : UIViewController<AsyncSocketDelegate>
{
AsyncSocket *asyncSocket;
}
@end
.m里面
Objective C code
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// NSError *err = nil;
// if(![asyncSocket connectToHost:@"192.168.1.105" onPort:18011 error:&err])
// {
// asyncSocket = [[AsyncSocket alloc] initWithDelegate:self];
//
// [asyncSocket setRunLoopModes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
//
// if (![self SocketOpen:@"192.168.1.105" port:18011])
// {
// NSMutableString *sendString=[NSMutableString stringWithCapacity:1000];
// [sendString appendString:@"非警务健身房"];
// NSData *cmdData = [sendString dataUsingEncoding:NSUTF8StringEncoding];
//
// [asyncSocket writeData:cmdData withTimeout:-1 tag:0];
// }
// NSLog(@"Error: %@", err);
// }
}
-(IBAction)haha:(id)sender{
asyncSocket=nil;
NSError *err = nil;
if(![asyncSocket connectToHost:@"192.168.1.105" onPort:18011 error:&err])
{
asyncSocket = [[AsyncSocket alloc] initWithDelegate:self];
[asyncSocket setRunLoopModes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
if (![self SocketOpen:@"192.168.1.105" port:18011])
{
NSMutableString *sendString=[NSMutableString stringWithCapacity:100000];
[sendString appendString:@"Socket测试成功!!!!"];
NSData *cmdData = [sendString dataUsingEncoding:NSUTF8StringEncoding];
[asyncSocket writeData:cmdData withTimeout:-1 tag:0];
}
NSLog(@"Error: %@", err);
}
}
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
NSLog(@"onSocket:%p didConnectToHost:%@ port:%hu", sock, host, port);
[sock readDataWithTimeout:1 tag:0];
}
-(void) onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
}
- (void)onSocket:(AsyncSocket *)sock didSecure:(BOOL)flag
{
NSLog(@"onSocket:%p didSecure:YES", sock);
}
- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
NSLog(@"onSocket:%p willDisconnectWithError:%@", sock, err);
}
- (void)onSocketDidDisconnect:(AsyncSocket *)sock
{
//断开连接了
NSLog(@"onSocketDidDisconnect:%p", sock);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
asyncSocket=nil;
}
//打开
- (NSInteger)SocketOpen:(NSString*)addr port:(NSInteger)port
{
if (![asyncSocket isConnected])
{
[asyncSocket connectToHost:addr onPort:port withTimeout:-1 error:nil];
NSLog(@"connect to Host:%@ Port:%d",addr,port);
}
return 0;
} |
|