iOS 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
- //
- //Createdbyxiangxivaon10-7-10.
- //Copyright2010__MyCompanyName__.Allrightsreserved.
- //
- #import<UIKit/UIKit.h>
- #import"AsyncSocket.h"
- #defineSRV_CONNECTED0
- #defineSRV_CONNECT_SUC1
- #defineSRV_CONNECT_FAIL2
- #[email protected]"192.168.110.1"
- #defineHOST_PORT8080
- @interfaceSocketDemoViewController:UIViewController{
- UITextField*inputMsg;
- UILabel*outputMsg;
- AsyncSocket*client;
- }
- @property(nonatomic,retain)AsyncSocket*client;
- @property(nonatomic,retain)IBOutletUITextField*inputMsg;
- @property(nonatomic,retain)IBOutletUILabel*outputMsg;
- -(int)connectServer:(NSString*)hostIPport:(int)hostPort;
- -(void)showMessage:(NSString*)msg;
- -(IBAction)sendMsg;
- -(IBAction)reConnect;
- -(IBAction)textFieldDoneEditing:(id)sender;
- -(IBAction)backgroundTouch:(id)sender;
- @end
- //
- //SocketDemoViewController.m
- //SocketDemo
- //
- //Createdbyxiangxivaon10-7-10.
- //Copyright2010__MyCompanyName__.Allrightsreserved.
- //
- #import"SocketDemoViewController.h"
- @implementationSocketDemoViewController
- @synthesizeinputMsg,outputMsg;
- @synthesizeclient;
- /*
- //Thedesignatedinitializer.Overridetoperformsetupthatisrequiredbeforetheviewisloaded.
- -(id)initWithNibName:(NSString*)nibNameOrNilbundle:(NSBundle*)nibBundleOrNil{
- self=[superinitWithNibName:nibNameOrNilbundle:nibBundleOrNil];
- if(self){
- //Custominitialization
- }
- returnself;
- }
- */
- /*
- //ImplementloadViewtocreateaviewhierarchyprogrammatically,withoutusinganib.
- -(void)loadView{
- }
- */
- //ImplementviewDidLoadtodoadditionalsetupafterloadingtheview,typicallyfromanib.
- -(void)viewDidLoad{
- //[superviewDidLoad];
- [selfconnectServer:HOST_IPport:HOST_PORT];
- //监听读取
- }
- //Overridetoalloworientationsotherthanthedefaultportraitorientation.
- -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
- returnYES;
- }
- -(void)didReceiveMemoryWarning{
- //Releasestheviewifitdoesn'thaveasuperview.
- [superdidReceiveMemoryWarning];
- //Releaseanycacheddata,images,etcthataren'tinuse.
- }
- -(void)viewDidUnload{
- self.client=nil;
- //Releaseanyretainedsubviewsofthemainview.
- //e.g.self.myOutlet=nil;
- }
- -(int)connectServer:(NSString*)hostIPport:(int)hostPort{
- if(client==nil){
- client=[[AsyncSocketalloc]initWithDelegate:self];
- NSError*err=nil;
- //192.168.110.128
- if(![clientconnectToHost:hostIPonPort:hostPorterror:&err]){
- NSLog(@"%@%@",[errcode],[errlocalizedDescription]);
- UIAlertView*alert=[[UIAlertViewalloc]initWithTitle:[@"Connectionfailedtohost"
- stringByAppendingString:hostIP]
- message:[[[NSStringalloc]initWithFormat:@"%@",[errcode]]stringByAppendingString:[errlocalizedDescription]]
- delegate:self
- cancelButtonTitle:@"OK"
- otherButtonTitles:nil];
- [alertshow];
- [alertrelease];
- //client=nil;
- returnSRV_CONNECT_FAIL;
- }else{
- NSLog(@"Conectou!");
- returnSRV_CONNECT_SUC;
- }
- }
- else{
- [clientreadDataWithTimeout:-1tag:0];
- returnSRV_CONNECTED;
- }
- }
- -(IBAction)reConnect{
- intstat=[selfconnectServer:HOST_IPport:HOST_PORT];
- switch(stat){
- caseSRV_CONNECT_SUC:
- [selfshowMessage:@"connectsuccess"];
- break;
- caseSRV_CONNECTED:
- [selfshowMessage:@"It'sconnected,don'tagian"];
- break;
- default:
- break;
- }
- }
- -(IBAction)sendMsg{
- NSString*inputMsgStr=self.inputMsg.text;
- NSString*content=[inputMsgStrstringByAppendingString:@"\r\n"];
- NSLog(@"%a",content);
- NSData*data=[contentdataUsingEncoding:NSISOLatin1StringEncoding];
- [clientwriteData:datawithTimeout:-1tag:0];
- //[datarelease];
- //[contentrelease];
- //[inputMsgStrrelease];
- //继续监听读取
- //[clientreadDataWithTimeout:-1tag:0];
- }
- #pragmamark-
- #pragmamarkcloseKeyboard
- -(IBAction)textFieldDoneEditing:(id)sender{
- [senderresignFirstResponder];
- }
- -(IBAction)backgroundTouch:(id)sender{
- [inputMsgresignFirstResponder];
- }
- #pragmamarksocketuitl
- -(void)showMessage:(NSString*)msg{
- UIAlertView*alert=[[UIAlertViewalloc]initWithTitle:@"Alert!"
- message:msg
- delegate:nil
- cancelButtonTitle:@"OK"
- otherButtonTitles:nil];
- [alertshow];
- [alertrelease];
- }
- #pragmamarksocketdelegate
- -(void)onSocket:(AsyncSocket*)sockdidConnectToHost:(NSString*)hostport:(UInt16)port{
- [clientreadDataWithTimeout:-1tag:0];
- }
- -(void)onSocket:(AsyncSocket*)sockwillDisconnectWithError:(NSError*)err
- {
- NSLog(@"Error");
- }
- -(void)onSocketDidDisconnect:(AsyncSocket*)sock
- {
- NSString*[email protected]"Sorrythisconnectisfailure";
- [selfshowMessage:msg];
- [msgrelease];
- client=nil;
- }
- -(void)onSocketDidSecure:(AsyncSocket*)sock{
- }
- -(void)onSocket:(AsyncSocket*)sockdidReadData:(NSData*)datawithTag:(long)tag{
- NSString*aStr=[[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];
- NSLog(@"Havareceiveddatasis:%@",aStr);
- self.outputMsg.text=aStr;
- [aStrrelease];
- [clientreadDataWithTimeout:-1tag:0];
- }
- #pragmamarkdealloc
- -(void)dealloc{
- [clientrelease];
- [inputMsgrelease];
- [outputMsgrelease];
- [superdealloc];
- }
- @end
还是先给出我的界面吧,否则很难懂这些代码
这样大家满意了吧!
好了说了这么多我们还是来看看代码究竟怎么回事吧。
首先从头文件开始看吧,
1,导入头文件#import "AsyncSocket.h",然后是一些宏
2,声明一个AsyncSocket对象,其他就是一些IBoutlet
再次我们看看视图加载,
- -(void)viewDidLoad{
- //[superviewDidLoad];
- [selfconnectServer:HOST_IPport:HOST_PORT];
- //监听读取
- }
在这个方法中,首先初始化我们的对象,使用代理的方式。对象显示是self。然后我们便需在我们的类中实现它的各种方法,来得到各种我们想得到的。
client = [[AsyncSocket alloc] initWithDelegate:self];
下面就是连接服务器了,
[client connectToHost:hostIP onPort:hostPort error:&err]
并且当client不为空时,我们就读取服务器的信息
[client readDataWithTimeout:-1 tag:0];
- -(void)onSocket:(AsyncSocket*)sockdidReadData:(NSData*)datawithTag:(long)tag{
- NSString*aStr=[[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];
- NSLog(@"Havareceiveddatasis:%@",aStr);
- self.outputMsg.text=aStr;
- [aStrrelease];
- [clientreadDataWithTimeout:-1tag:0];
- }
在这个方法中很耐人寻味,主要就是在于递归的调用。
- -(IBAction)sendMsg{
- NSString*inputMsgStr=self.inputMsg.text;
- NSString*content=[inputMsgStrstringByAppendingString:@"\r\n"];
- NSLog(@"%a",content);
- NSData*data=[contentdataUsingEncoding:NSISOLatin1StringEncoding];
- [clientwriteData:datawithTimeout:-1tag:0];
- }
我们在看看上面发送消息的代码,中的在于"\r\n"的拼接,否则在java端的程序,无法知道你发过来的信息是否结束,当然你也可以使用其他的方式来读取客户端,比如定时;但是我在java端写的server是readLine来判断的,所以需要拼接这个\r\n.
其他的代码除了asyncSocket代理外都是我们所熟悉的。
- -(void)onSocket:(AsyncSocket*)sockdidConnectToHost:(NSString*)hostport:(UInt16)port{
- [clientreadDataWithTimeout:-1tag:0];
- }
- -(void)onSocket:(AsyncSocket*)sockwillDisconnectWithError:(NSError*)err
- {
- NSLog(@"Error");
- }
- -(void)onSocketDidDisconnect:(AsyncSocket*)sock
- {
- NSString*[email protected]"Sorrythisconnectisfailure";
- [selfshowMessage:msg];
- [msgrelease];
- client=nil;
- }
- -(void)onSocketDidSecure:(AsyncSocket*)sock{
- }
- -(void)onSocket:(AsyncSocket*)sockdidReadData:(NSData*)datawithTag:(long)tag{
- NSString*aStr=[[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];
- NSLog(@"Havareceiveddatasis:%@",aStr);
- self.outputMsg.text=aStr;
- [aStrrelease];
- [clientreadDataWithTimeout:-1tag:0];
- }
到此就结束了。