iphone的标准推荐CFNetwork C库编程.但是编程比较烦躁。在其它OS往往用类来封装的对Socket函数的处理。比如MFC的CAsysncSocket.在iphone也有类似于开源项目.cocoa AsyncSocket库, 官方网站:http://code.google.com/p/cocoaasyncsocket/ 它用来简化CFnetwork的调用.
一.在项目引入ASyncSocket库
1.下载ASyncSocket库源码
2.把ASyncSocket库源码加入项目:只需要增加RunLoop目录中的AsyncSocket.h、AsyncSocket.m、AsyncUdpSocket.h和AsyncUdpSocket.m四个文件。
3.在项目增加CFNetwork框架
在Framework目录右健,选择Add-->Existing Files... , 选择 CFNetwork.framework
二.TCP客户端
1. 在controller头文件定义AsyncSocket对象
#import <UIKit/UIKit.h>
#import "AsyncSocket.h"
@interface HelloiPhoneViewController : UIViewController {
UITextField * textField;
AsyncSocket * asyncSocket;
}
@property (retain, nonatomic) IBOutlet UITextField *textField;
- (IBAction) buttonPressed: (id)sender;
- (IBAction) textFieldDoneEditing: (id)sender;
@end
2.在需要联接地方使用connectToHost联接服务器
其中initWithDelegate的参数中self是必须。这个对象指针中的各个Socket响应的函数将被ASyncSocket所调用.
asyncSocket = [[AsyncSocket alloc] initWithDelegate:self];
NSError *err = nil;
if(![asyncSocket connectToHost:host on:port error:&err])
{
NSLog(@"Error: %@", err);
}
3.增加Socket响应事件
因为initWithDelegate把将当前对象传递进去,这样只要在当前对象方法实现相应方法.
4.关于NSData对象
无论SOCKET收发都采用NSData对象.它的定义是 http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/Reference/Reference.html
NSData主要是带一个(id)data指向的数据空间和长度 length.
NSString 转换成NSData 对象
NSData* xmlData = [@"testdata" dataUsingEncoding:NSUTF8StringEncoding];
NSData 转换成NSString对象
NSData * data;
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
4.发送数据
AsyncSocket writeData 方法来发送数据,它有如下定义
- (void)writeData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag;
以下是一个实例语句.
NSData* aData= [@"test data" dataUsingEncoding: NSUTF8StringEncoding];
[sock writeData:aData withTimeout:-1 tag:1];
在onSocket重载函数,有如定义采用是专门用来处理SOCKET的发送数据的:
-(void)onSocket(AsyncSocket *)sock didWriteDataWithTag:(long)tag
{
NSLog(@"thread(%),onSocket:%p didWriteDataWithTag:%d",[[NSThread currentThread] name],
sock,tag);
}
5.接收Socket数据.
在onSocket重载函数,有如定义采用是专门用来处理SOCKET的接收数据的.
-(void) onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
在中间将其转换成NSString进行显示.
NSString* aStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"===%@",aStr);
[aStr release];
在iphone的平台下,要进行socket开发其实有很多种的方法,开源的库Asyncsocket,官方的CFSocket,还有BSD的socket。
下面是用开源的库Asyncsocket的例子:
- //
- // SocketDemoViewController.h
- // SocketDemo
- //
- // Created by xiang xiva on 10-7-10.
- // Copyright 2010 __MyCompanyName__. All rights reserved.
- //
- #import <UIKit/UIKit.h>
- #import "AsyncSocket.h"
- #define SRV_CONNECTED 0
- #define SRV_CONNECT_SUC 1
- #define SRV_CONNECT_FAIL 2
- #define HOST_IP @"192.168.110.1"
- #define HOST_PORT 8080
- @interface SocketDemoViewController : UIViewController {
- UITextField *inputMsg;
- UILabel *outputMsg;
- AsyncSocket *client;
- }
- @property (nonatomic, retain) AsyncSocket *client;
- @property (nonatomic, retain) IBOutlet UITextField *inputMsg;
- @property (nonatomic, retain) IBOutlet UILabel *outputMsg;
- - (int) connectServer: (NSString *) hostIP port:(int) hostPort;
- - (void) showMessage:(NSString *) msg;
- - (IBAction) sendMsg;
- - (IBAction) reConnect;
- - (IBAction) textFieldDoneEditing:(id)sender;
- - (IBAction) backgroundTouch:(id)sender;
- @end
- //
- // SocketDemoViewController.m
- // SocketDemo
- //
- // Created by xiang xiva on 10-7-10.
- // Copyright 2010 __MyCompanyName__. All rights reserved.
- //
- #import "SocketDemoViewController.h"
- @implementation SocketDemoViewController
- @synthesize inputMsg, outputMsg;
- @synthesize client;
- /*
- // The designated initializer. Override to perform setup that is required before the view is loaded.
- - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
- self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
- if (self) {
- // Custom initialization
- }
- return self;
- }
- */
- /*
- // Implement loadView to create a view hierarchy programmatically, without using a nib.
- - (void)loadView {
- }
- */
- // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- - (void)viewDidLoad {
- //[super viewDidLoad];
- [self connectServer:HOST_IP port:HOST_PORT];
- //监听读取
- }
- // Override to allow orientations other than the default portrait orientation.
- - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
- return YES;
- }
- - (void)didReceiveMemoryWarning {
- // Releases the view if it doesn't have a superview.
- [super didReceiveMemoryWarning];
- // Release any cached data, images, etc that aren't in use.
- }
- - (void)viewDidUnload {
- self.client = nil;
- // Release any retained subviews of the main view.
- // e.g. self.myOutlet = nil;
- }
- - (int) connectServer: (NSString *) hostIP port:(int) hostPort{
- if (client == nil) {
- client = [[AsyncSocket alloc] initWithDelegate:self];
- NSError *err = nil;
- //192.168.110.128
- if (![client connectToHost:hostIP onPort:hostPort error:&err]) {
- NSLog(@"%@ %@", [err code], [err localizedDescription]);
- UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[@"Connection failed to host "
- stringByAppendingString:hostIP]
- message:[[[NSString alloc]initWithFormat:@"%@",[err code]] stringByAppendingString:[err localizedDescription]]
- delegate:self
- cancelButtonTitle:@"OK"
- otherButtonTitles:nil];
- [alert show];
- [alert release];
- //client = nil;
- return SRV_CONNECT_FAIL;
- } else {
- NSLog(@"Conectou!");
- return SRV_CONNECT_SUC;
- }
- }
- else {
- [client readDataWithTimeout:-1 tag:0];
- return SRV_CONNECTED;
- }
- }
- - (IBAction) reConnect{
- int stat = [self connectServer:HOST_IP port:HOST_PORT];
- switch (stat) {
- case SRV_CONNECT_SUC:
- [self showMessage:@"connect success"];
- break;
- case SRV_CONNECTED:
- [self showMessage:@"It's connected,don't agian"];
- break;
- default:
- break;
- }
- }
- - (IBAction) sendMsg{
- NSString *inputMsgStr = self.inputMsg.text;
- NSString * content = [inputMsgStr stringByAppendingString:@"\r\n"];
- NSLog(@"%a",content);
- NSData *data = [content dataUsingEncoding:NSISOLatin1StringEncoding];
- [client writeData:data withTimeout:-1 tag:0];
- //[data release];
- //[content release];
- //[inputMsgStr release];
- //继续监听读取
- //[client readDataWithTimeout:-1 tag:0];
- }
- #pragma mark -
- #pragma mark close Keyboard
- - (IBAction) textFieldDoneEditing:(id)sender{
- [sender resignFirstResponder];
- }
- - (IBAction) backgroundTouch:(id)sender{
- [inputMsg resignFirstResponder];
- }
- #pragma mark socket uitl
- - (void) showMessage:(NSString *) msg{
- UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"Alert!"
- message:msg
- delegate:nil
- cancelButtonTitle:@"OK"
- otherButtonTitles:nil];
- [alert show];
- [alert release];
- }
- #pragma mark socket delegate
- - (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port{
- [client readDataWithTimeout:-1 tag:0];
- }
- - (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
- {
- NSLog(@"Error");
- }
- - (void)onSocketDidDisconnect:(AsyncSocket *)sock
- {
- NSString *msg = @"Sorry this connect is failure";
- [self showMessage:msg];
- [msg release];
- client = nil;
- }
- - (void)onSocketDidSecure:(AsyncSocket *)sock{
- }
- - (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
- NSString* aStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
- NSLog(@"Hava received datas is :%@",aStr);
- self.outputMsg.text = aStr;
- [aStr release];
- [client readDataWithTimeout:-1 tag:0];
- }
- #pragma mark dealloc
- - (void)dealloc {
- [client release];
- [inputMsg release];
- [outputMsg release];
- [super dealloc];
- }
- @end