iPhone的Socket编程使用开源代码之AsyncSocket

假如你也是一个java程序员,而你又不是很懂Socket。

下面我的这篇文章也许能帮助你一些。

http://xiva.iteye.com/blog/993336

 

首先我们写好上面文章中的server端。

下面我们可以访问一下下面的地址:

 

http://code.google.com/p/cocoaasyncsocket/

这是一个开源框架。呵,不知道拿到自己程序中使用是否涉及侵权。

但是这句话“The CocoaAsyncSocket project is in the public domain.”是我有信心使用它们的源码,否则只能自己用c来写了,或者使用CFSocket、CFNetwork等类自己来写了。不过也无妨,应在在使用线程的情况下,我们也是可以实现的。

 

总之,为了开发的便捷,我使用了AsyncSocket这个类,这样可以异步通信。

 

建立一个基于视图的应用程序,按照http://code.google.com/p/cocoaasyncsocket/wiki/Reference_AsyncSocket

我们AsyncSocket.h和AsyncSocket.m到我们的项目中,并且导入CFNetwork.framework。这样基本准备工作就做好了。

 

下面提供我的应用中的代码以及界面图:

 

//
//  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

 

 

 

还是先给出我的界面吧,否则很难懂这些代码

iPad界面

 

 

这样大家满意了吧!

 

好了说了这么多我们还是来看看代码究竟怎么回事吧。

首先从头文件开始看吧,

1,导入头文件#import "AsyncSocket.h",然后是一些宏

2,声明一个AsyncSocket对象,其他就是一些IBoutlet

再次我们看看视图加载,

 

 

- (void)viewDidLoad {
    //[super viewDidLoad];
	[self connectServer:HOST_IP port:HOST_PORT];
	//监听读取
	
}

 显然我们调用了connectServer::这个方法。

在这个方法中,首先初始化我们的对象,使用代理的方式。对象显示是self。然后我们便需在我们的类中实现它的各种方法,来得到各种我们想得到的。

client = [[AsyncSocket alloc] initWithDelegate:self];

 

下面就是连接服务器了,

[client connectToHost:hostIP onPort:hostPort error:&err]

 

并且当client不为空时,我们就读取服务器的信息

[client readDataWithTimeout:-1 tag:0];

 

 

 

- (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];
}

 

 

在这个方法中很耐人寻味,主要就是在于递归的调用。

 

 

- (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];
}

 我们在看看上面发送消息的代码,中的在于"\r\n"的拼接,否则在java端的程序,无法知道你发过来的信息是否结束,当然你也可以使用其他的方式来读取客户端,比如定时;但是我在java端写的server是readLine来判断的,所以需要拼接这个\r\n.

 

 

其他的代码除了asyncSocket代理外都是我们所熟悉的。

 

- (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];
}

 

到此就结束了。

 

其他要说的,明天再完善吧。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值