您的位置:首页 > 编程语言

Socket编程——第三方类库 AsyncSocket

2015-12-04 21:49 323 查看
在这里,是调用第三方的一个开源类库来实现Socket编程。网址为:http://code.google.com/p/cocoaasyncsocket/

一,导入ASyncSocket库

将下载下来的文件中,Source文件夹里面的AsyncSocket.h、AsyncSocket.m、AsyncUdpSocket.h和AsyncUdpSocket.m四个文件复制到你的工程里面。然后工程中加入一个类库CFNetwork.framework,

二,客户端的程序

1,导入.h文件并定义AsyncSocket对象

#import "AsyncSocket.h"
@property (nonatomic, retain) AsyncSocket *client;


2,在viewDidLoad中进行监听读取

[self connectServer:HOST_IP port:HOST_PORT];


3,链接服务器

- (int) connectServer: (NSString *) hostIP port:(int) hostPort{
if (client == nil) {
client = [[AsyncSocket alloc]initWithDelegate:self];
NSError *err = nil;
if (![client connectToHost:hostIP onPort:hostPort error:&err]) {
NSLog(@"%ld %@", (long)[err code], [err localizedDescription]);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[@"Connection failed to host "
stringByAppendingString:hostIP]
message:[[[NSString alloc]initWithFormat:@"%ld",(long)[err code]] stringByAppendingString:[err localizedDescription]]                                 delegate:self                                cancelButtonTitle:@"OK"                       otherButtonTitles:nil];
[alert show];
return SRV_CONNECT_FAIL;
} else {
return SRV_CONNECT_SUC;
}
}
else {
[client readDataWithTimeout:-1 tag:0];
return SRV_CONNECTED;
}
}


4,连接成功和连接失败的函数

//连接成功后读取数据
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port{
[client readDataWithTimeout:-1 tag:0];
}
//连接失败则返回error
- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
NSLog(@"Error");
}
- (void)onSocketDidDisconnect:(AsyncSocket *)sock
{
NSString *msg = @"Sorry this connect is failure";
[AlertView showNotice:msg];
client = nil;
}


5,读取数据

- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{

_aStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Hava received datas is :%@",_aStr);
flag = 1;
[client readDataWithTimeout:-1 tag:0];
}


6,写数据

NSData *data0 = [@"1" dataUsingEncoding:NSUTF8StringEncoding];
[client writeData:data0 withTimeout:-1 tag:1];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  socket 编程 iOS