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
- //
- // 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
还是先给出我的界面吧,否则很难懂这些代码

这样大家满意了吧!
好了说了这么多我们还是来看看代码究竟怎么回事吧。
首先从头文件开始看吧,
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];
- }
到此就结束了。
iOS Socket第三方开源类库 ----AsyncSocket的更多相关文章
- iOS Socket第三方开源类库 ----AsyncSocket 分类: ios相关 ios技术 2015-03-11 22:14 59人阅读 评论(0) 收藏
假如你也是一个java程序员,而你又不是很懂Socket. 下面我的这篇文章也许能帮助你一些. http://xiva.iteye.com/blog/993336 首先我们写好上面文章中的server ...
- IOS常用第三方开源类库&组件
1.AFNetworking AFNetworking 采用 NSURLConnection + NSOperation, 主要方便与服务端 API 进行数据交换, 操作简单, 功能强大, 现在许多人 ...
- 使用CocoaPods管理第三方开源类库
iOS开发中经常会用到许多第三方开源类库,比如AFNetworking.FMDB.JSONKit等等,使用CocoaPods这个工具就能很方便得对工程中用到的类库进行管理,包括自动下载配置以及更新. ...
- iOS常用第三方开源框架和优秀开发者博客等
博客收藏iOS开发过程好的开源框架.开源项目.Xcode工具插件.Mac软件.文章等,会不断更新维护,希望对你们有帮助.如果有推荐或者建议,请到此处提交推荐或者联系我. 该文档已提交GitHub,点击 ...
- iOS - CocoaPods 第三方开源框架管理
1.CocoaPods CocoaPods 是一个负责管理 iOS 项目中第三方开源库的工具.CocoaPods 的项目源码在 Github 上管理.该项目开始于 2011 年 8 月 12 日,在这 ...
- [IOS A] - 一些开源类库
因 为iOS SDK相对比较底层,所以开发者就得受累多做一些体力活.不过幸运的是,有很多第三方的类库可以用来简化很多不必要的工作.笔者整理了一下在本人学习过程 中用到的一些比较有用Objective- ...
- iOS常用的开源类库
开发几个常用的开源类库及下载地址: 引用 1.json json编码解码 2.GTMBase64 base64编码解码 3.TouchXML xml解析 4.SFHFKeychainUtils 安全保 ...
- iOS socket编程 第三方库 AsyncSocket(GCDAsyncSocket)
Socket描述了一个IP.端口对.它简化了程序员的操作,知道对方的IP以及PORT就可以给对方发送消息,再由服务器端来处理发送的这些消息.所以,Socket一定包含了通信的双发,即客户端(Clien ...
- 最全面的iOS和Mac开源项目和第三方库汇总
标签: UI 下拉刷新 EGOTableViewPullRefresh – 最早的下拉刷新控件. SVPullToRefresh – 下拉刷新控件. MJRefresh – 仅需一行代码就可以为UIT ...
随机推荐
- 在WIN7/8下把XP装入VHD (上)
系统平台:win8.1 操作目的:工作中需要使用一个只能在winxp下运行的软件,但我平时都用win8.1,也不想弄个麻烦的双系统.在无忧论坛研究了两天后找到个比较好的办法,在VHD里装个window ...
- Log4j NDC MDC
NDC(Nested Diagnostic Context)和MDC(Mapped Diagnostic Context)是log4j种非常有用的两个类,它们用于存储应用程序的上下文信息(contex ...
- 转:Loadrunner——Simulate a new user on each iteration设置
最近在与大家的讨论中发现了LoadRunner的很多问题,出于解决问题的出发点,我也就相关自己不理解的问题在Google中搜索了一番,并通过一些实例也去实际操作了一遍,发现很多问题确实并不是那么难解决 ...
- 分享一款CSS框架
1.http://bulma.io/documentation/elements 2.支持IE9+ 3.内容:
- Linux 下 git的使用
参考链接:http://www.liaoxuefeng.com 安装 安装步骤: ①先给操作系统装入git工具,以Linux为例: $ sudo apt-get install git ②去githu ...
- PAT1027
People in Mars represent the colors in their computers in a similar way as the Earth people. 火星人在他们的 ...
- 剑指offer之有序二维数组查找
大多数人注意到元素是行列有序的,会马上想到对每行(或列)进行二分查找,每行(或列)需要logN时间,N行(或列)共需要NlogN时间,很容易写出如下代码 1 2 3 4 5 6 7 8 9 10 11 ...
- Apache多端口配置
修改http.conf监听多个端口 Listen 80 Listen 8001 Listen 8002 配置站点 <VirtualHost *:8001> ServerName *:800 ...
- 【转载】区间DP
http://www.cnblogs.com/zsboy/archive/2013/03/08/2950261.html 博客园 首页 新随笔 联系 订阅 管理 定义区间DP 区间动态规划问题一般 ...
- 选择LDO的方法(转)
http://www.micro-bridge.com/news/sort.asp?dy1=技术资料&dy2=产品相关资料&page=2 作者:LANDA PHAM 来源:德州仪器 ...