我想要再ipad程序裡面,用代碼給打印機發送一段字符串,然後打印。
各位,我的問題沒有說清楚,不好意思。
情況是這樣的,我現在想要連接到打印機,wifi的,然後給打印機發送一個字符串去打印。連接打印機不知道怎麼連接,然後發送消息這個也不知道咋整。各位幫幫忙。
打印機和ipad在同一個局域網下,想用socket通過打印機的ip地址進行傳送要打印的內容。
.h 裡面
#import <UIKit/UIKit.h>
#import "AsyncSocket.h"
@interface ViewController : UIViewController<AsyncSocketDelegate>
{
AsyncSocket *asyncSocket;
}
@end
.m裡面
#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;
}