注:本篇文章参考自http://no001.blog.51cto.com/1142339/555344/
使用方法如下:
1、创建工程。
2、把AsyncSocket添加到项目中。
3、添加CFNetwork.framework到工程中。
4、实现测试类:
#import
#import "AsyncSocket.h"
@interface iphone_socketViewController : UIViewController {
AsyncSocket *asyncSocket;
}
@end
相应的方法实现:
#import "iphone_socketViewController.h"
@implementation iphone_socketViewController
- (void)viewDidLoad {
[super viewDidLoad];
asyncSocket = [[AsyncSocket alloc] initWithDelegate:self];
NSError *err = nil;
if(![asyncSocket connectToHost:@"192.168.0.113" onPort:25001 error:&err])
{
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
{
NSString* aStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"===%@",aStr);
[aStr release];
NSData* aData= [@"我喜欢你" dataUsingEncoding: NSUTF8StringEncoding];
[sock writeData:aData withTimeout:-1 tag:1];
[sock readDataWithTimeout:1 tag:0];
}
- (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;
}
- (void)dealloc {
[asyncSocket release];
}
@end