iOS Socket第三方开源类库 ----AsyncSocket 分类: ios相关 ios技术 2015-03-11 22:14 59人阅读 评论(0) 收藏
假如你也是一个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相关 ios技术 2015-03-11 22:14 59人阅读 评论(0) 收藏的更多相关文章
- NYOJ-975 关于521 AC 分类: NYOJ 2014-02-25 22:14 349人阅读 评论(0) 收藏
#include<stdio.h> struct AC { int x,y; }a[1000004]; int main() { int i,j,k=0;a[125].x=1,a[521] ...
- iOS Socket第三方开源类库 ----AsyncSocket
假如你也是一个java程序员,而你又不是很懂Socket. 下面我的这篇文章也许能帮助你一些. http://xiva.iteye.com/blog/993336 首先我们写好上面文章中的server ...
- 全方位分析Objcetive-C Runtime 分类: ios技术 2015-03-11 22:29 77人阅读 评论(0) 收藏
本文详细整理了 Cocoa 的 Runtime 系统的知识,它使得 Objective-C 如虎添翼,具备了灵活的动态特性,使这门古老的语言焕发生机.主要内容如下: 引言 简介 与Runtime交互 ...
- Run Loop简介 分类: ios技术 ios相关 2015-03-11 22:21 73人阅读 评论(0) 收藏
做了一年多的IOS开发,对IOS和Objective-C深层次的了解还十分有限,大多还停留在会用API的级别,这是件挺可悲的事情.想学好一门语言还是需要深层次的了解它,这样才能在使用的时候得心应手,出 ...
- IOS之富文本编辑 分类: ios技术 2015-03-06 22:51 89人阅读 评论(0) 收藏
之前做项目时遇到一个问题: 使用UITextView显示一段电影的简介,由于字数比较多,所以字体设置的很小,行间距和段间距也很小,一大段文字挤在一起看起来很别扭,想要把行间距调大,结 ...
- iOS纯代码手动适配 分类: ios技术 2015-05-04 17:14 239人阅读 评论(0) 收藏
首先说下让自己的程序支持iPhone6和6+,第一种使用官方提供的launch screen.xib,这个直接看官方文档即可,这里不再多述:第二种方法是和之前iPhone5的类似,比较简单,为iPho ...
- UI基础:视图控制器.屏幕旋转.MVC 分类: iOS学习-UI 2015-07-02 22:21 62人阅读 评论(0) 收藏
UIViewController 视图控制器,继承自UIResponder,作用:管理视图并且响应事件 功能: 1.分担APPdelegate的工作 2.实现模块独立,能提高复用性 创建UIViewC ...
- UI基础:UI程序执行顺序(UIApplicationMain()函数),自定义视图 分类: iOS学习-UI 2015-07-02 22:09 68人阅读 评论(0) 收藏
UI程序的一般执行顺序: 先进入main里面,执行函数UIApplicationMain(),通过该函数创建应用程序对象和指定其代理并实现监听,当执行函数UIApplicationMain()时还会做 ...
- C语言基础:枚举.宏 分类: iOS学习 c语言基础 2015-06-10 22:01 20人阅读 评论(0) 收藏
枚举:一组有符号的整型常量,一 一列举所有的状态 枚举常和switch连用 enum week{ monday=1, tuesday, wednesday, thursday, friday, sat ...
随机推荐
- 学习笔记——建造者模式Builder
构造者模式.外部场景如果需要一个汽车类,它不需要关心如何构造,它只需要告诉Director需要什么,就可以从Director获得. 如:CDirector(IBuilder* aBuilder); 场 ...
- 转:Loadrunner打开https报错“Internet…
Loadrunner 录制htpps 协议通过IE打开页面,报错“Internet Explorer cannot display the webpage”. 但是直接打开IE不通过 loadrunn ...
- PAT (Advanced Level) 1097. Deduplication on a Linked List (25)
简单题. #include<cstdio> #include<cstring> #include<cmath> #include<vector> #in ...
- 转博客至github
呃呃呃,当初是从新浪博客转过来的,现在发现github的静态博客对我来说用起来更方便. 转至github,这里的东西以后有空会一点一点移过去. http://jcf94.github.io
- 浅谈ajax的优点与缺点
AJAX (Asynchronous Javascript and XML) 是一种交互式动态web应用开发技术,该技术能提供富用户体验. 完全的AJAX应用给人以桌面应用的感觉.正如其他任何技术,A ...
- Nginx 502/504 Gateway time-out错误完美解决方案【转发】
在安装完Nginx+PHP-fpm+Mysql后,跑PHP的应用会经常出现504 Gateway Time-out 或者502 Bad Gateway的情况. Nginx 504 Gateway ...
- 以前的loginUI
的 <%@ page language="java" pageEncoding="UTF-8"%> <%@ include file=&quo ...
- Vsftp配置都没有问题 连接不上 530 Login incorrect 解决方法
客户端输入正确的用户名和密码之后,却一直显示:530 Login incorrectLogin Failed后来发现在etc下面有个pam.d文件夹进去打开vsftpd这个文件, 发现里面对之前的用户 ...
- jQuery笔记(1)
jQuery 是一个类库 拥有众多js函数的类库 jQuery 大大简化了js的书写代码,看的舒服,用的爽. jQuery 是一个数组,它能够隐性的遍历. 比如 ${"button" ...
- MyEclipse8.5 无法安装ADT解决办法
打开MYECLIPSE.点击菜单栏的help ->my eclipse configure center .然后add site 指向 https://dl-ssl.google.com/an ...