假如你也是一个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代码  
  1. //
  2. //  SocketDemoViewController.h
  3. //  SocketDemo
  4. //
  5. //  Created by xiang xiva on 10-7-10.
  6. //  Copyright 2010 __MyCompanyName__. All rights reserved.
  7. //
  8. #import <UIKit/UIKit.h>
  9. #import "AsyncSocket.h"
  10. #define SRV_CONNECTED 0
  11. #define SRV_CONNECT_SUC 1
  12. #define SRV_CONNECT_FAIL 2
  13. #define HOST_IP @"192.168.110.1"
  14. #define HOST_PORT 8080
  15. @interface SocketDemoViewController : UIViewController {
  16. UITextField *inputMsg;
  17. UILabel *outputMsg;
  18. AsyncSocket *client;
  19. }
  20. @property (nonatomic, retain) AsyncSocket *client;
  21. @property (nonatomic, retain) IBOutlet UITextField *inputMsg;
  22. @property (nonatomic, retain) IBOutlet UILabel *outputMsg;
  23. - (int) connectServer: (NSString *) hostIP port:(int) hostPort;
  24. - (void) showMessage:(NSString *) msg;
  25. - (IBAction) sendMsg;
  26. - (IBAction) reConnect;
  27. - (IBAction) textFieldDoneEditing:(id)sender;
  28. - (IBAction) backgroundTouch:(id)sender;
  29. @end
socketdemoviewcontroller.m代码  
  1. //
  2. //  SocketDemoViewController.m
  3. //  SocketDemo
  4. //
  5. //  Created by xiang xiva on 10-7-10.
  6. //  Copyright 2010 __MyCompanyName__. All rights reserved.
  7. //
  8. #import "SocketDemoViewController.h"
  9. @implementation SocketDemoViewController
  10. @synthesize inputMsg, outputMsg;
  11. @synthesize client;
  12. /*
  13. // The designated initializer. Override to perform setup that is required before the view is loaded.
  14. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
  15. self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  16. if (self) {
  17. // Custom initialization
  18. }
  19. return self;
  20. }
  21. */
  22. /*
  23. // Implement loadView to create a view hierarchy programmatically, without using a nib.
  24. - (void)loadView {
  25. }
  26. */
  27. // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
  28. - (void)viewDidLoad {
  29. //[super viewDidLoad];
  30. [self connectServer:HOST_IP port:HOST_PORT];
  31. //监听读取
  32. }
  33. // Override to allow orientations other than the default portrait orientation.
  34. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
  35. return YES;
  36. }
  37. - (void)didReceiveMemoryWarning {
  38. // Releases the view if it doesn't have a superview.
  39. [super didReceiveMemoryWarning];
  40. // Release any cached data, images, etc that aren't in use.
  41. }
  42. - (void)viewDidUnload {
  43. self.client = nil;
  44. // Release any retained subviews of the main view.
  45. // e.g. self.myOutlet = nil;
  46. }
  47. - (int) connectServer: (NSString *) hostIP port:(int) hostPort{
  48. if (client == nil) {
  49. client = [[AsyncSocket alloc] initWithDelegate:self];
  50. NSError *err = nil;
  51. //192.168.110.128
  52. if (![client connectToHost:hostIP onPort:hostPort error:&err]) {
  53. NSLog(@"%@ %@", [err code], [err localizedDescription]);
  54. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[@"Connection failed to host "
  55. stringByAppendingString:hostIP]
  56. message:[[[NSString alloc]initWithFormat:@"%@",[err code]] stringByAppendingString:[err localizedDescription]]
  57. delegate:self
  58. cancelButtonTitle:@"OK"
  59. otherButtonTitles:nil];
  60. [alert show];
  61. [alert release];
  62. //client = nil;
  63. return SRV_CONNECT_FAIL;
  64. } else {
  65. NSLog(@"Conectou!");
  66. return SRV_CONNECT_SUC;
  67. }
  68. }
  69. else {
  70. [client readDataWithTimeout:-1 tag:0];
  71. return SRV_CONNECTED;
  72. }
  73. }
  74. - (IBAction) reConnect{
  75. int stat = [self connectServer:HOST_IP port:HOST_PORT];
  76. switch (stat) {
  77. case SRV_CONNECT_SUC:
  78. [self showMessage:@"connect success"];
  79. break;
  80. case SRV_CONNECTED:
  81. [self showMessage:@"It's connected,don't agian"];
  82. break;
  83. default:
  84. break;
  85. }
  86. }
  87. - (IBAction) sendMsg{
  88. NSString *inputMsgStr = self.inputMsg.text;
  89. NSString * content = [inputMsgStr stringByAppendingString:@"\r\n"];
  90. NSLog(@"%a",content);
  91. NSData *data = [content dataUsingEncoding:NSISOLatin1StringEncoding];
  92. [client writeData:data withTimeout:-1 tag:0];
  93. //[data release];
  94. //[content release];
  95. //[inputMsgStr release];
  96. //继续监听读取
  97. //[client readDataWithTimeout:-1 tag:0];
  98. }
  99. #pragma mark -
  100. #pragma mark close Keyboard
  101. - (IBAction) textFieldDoneEditing:(id)sender{
  102. [sender resignFirstResponder];
  103. }
  104. - (IBAction) backgroundTouch:(id)sender{
  105. [inputMsg resignFirstResponder];
  106. }
  107. #pragma mark socket uitl
  108. - (void) showMessage:(NSString *) msg{
  109. UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"Alert!"
  110. message:msg
  111. delegate:nil
  112. cancelButtonTitle:@"OK"
  113. otherButtonTitles:nil];
  114. [alert show];
  115. [alert release];
  116. }
  117. #pragma mark socket delegate
  118. - (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port{
  119. [client readDataWithTimeout:-1 tag:0];
  120. }
  121. - (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
  122. {
  123. NSLog(@"Error");
  124. }
  125. - (void)onSocketDidDisconnect:(AsyncSocket *)sock
  126. {
  127. NSString *msg = @"Sorry this connect is failure";
  128. [self showMessage:msg];
  129. [msg release];
  130. client = nil;
  131. }
  132. - (void)onSocketDidSecure:(AsyncSocket *)sock{
  133. }
  134. - (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
  135. NSString* aStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  136. NSLog(@"Hava received datas is :%@",aStr);
  137. self.outputMsg.text = aStr;
  138. [aStr release];
  139. [client readDataWithTimeout:-1 tag:0];
  140. }
  141. #pragma mark dealloc
  142. - (void)dealloc {
  143. [client release];
  144. [inputMsg release];
  145. [outputMsg release];
  146. [super dealloc];
  147. }
  148. @end

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

这样大家满意了吧!

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

首先从头文件开始看吧,

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

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

再次我们看看视图加载,

Java代码  
  1. - (void)viewDidLoad {
  2. //[super viewDidLoad];
  3. [self connectServer:HOST_IP port:HOST_PORT];
  4. //监听读取
  5. }

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

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

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

下面就是连接服务器了,

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

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

[client readDataWithTimeout:-1 tag:0];

Java代码  
  1. - (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
  2. NSString* aStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  3. NSLog(@"Hava received datas is :%@",aStr);
  4. self.outputMsg.text = aStr;
  5. [aStr release];
  6. [client readDataWithTimeout:-1 tag:0];
  7. }

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

Sendmsg代码  
  1. - (IBAction) sendMsg{
  2. NSString *inputMsgStr = self.inputMsg.text;
  3. NSString * content = [inputMsgStr stringByAppendingString:@"\r\n"];
  4. NSLog(@"%a",content);
  5. NSData *data = [content dataUsingEncoding:NSISOLatin1StringEncoding];
  6. [client writeData:data withTimeout:-1 tag:0];
  7. }

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

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

这些都是asyncsocket代理的代码  
  1. - (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port{
  2. [client readDataWithTimeout:-1 tag:0];
  3. }
  4. - (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
  5. {
  6. NSLog(@"Error");
  7. }
  8. - (void)onSocketDidDisconnect:(AsyncSocket *)sock
  9. {
  10. NSString *msg = @"Sorry this connect is failure";
  11. [self showMessage:msg];
  12. [msg release];
  13. client = nil;
  14. }
  15. - (void)onSocketDidSecure:(AsyncSocket *)sock{
  16. }
  17. - (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
  18. NSString* aStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  19. NSLog(@"Hava received datas is :%@",aStr);
  20. self.outputMsg.text = aStr;
  21. [aStr release];
  22. [client readDataWithTimeout:-1 tag:0];
  23. }

到此就结束了。

iOS Socket第三方开源类库 ----AsyncSocket 分类: ios相关 ios技术 2015-03-11 22:14 59人阅读 评论(0) 收藏的更多相关文章

  1. 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] ...

  2. iOS Socket第三方开源类库 ----AsyncSocket

    假如你也是一个java程序员,而你又不是很懂Socket. 下面我的这篇文章也许能帮助你一些. http://xiva.iteye.com/blog/993336 首先我们写好上面文章中的server ...

  3. 全方位分析Objcetive-C Runtime 分类: ios技术 2015-03-11 22:29 77人阅读 评论(0) 收藏

    本文详细整理了 Cocoa 的 Runtime 系统的知识,它使得 Objective-C 如虎添翼,具备了灵活的动态特性,使这门古老的语言焕发生机.主要内容如下: 引言 简介 与Runtime交互 ...

  4. Run Loop简介 分类: ios技术 ios相关 2015-03-11 22:21 73人阅读 评论(0) 收藏

    做了一年多的IOS开发,对IOS和Objective-C深层次的了解还十分有限,大多还停留在会用API的级别,这是件挺可悲的事情.想学好一门语言还是需要深层次的了解它,这样才能在使用的时候得心应手,出 ...

  5. IOS之富文本编辑 分类: ios技术 2015-03-06 22:51 89人阅读 评论(0) 收藏

    之前做项目时遇到一个问题:          使用UITextView显示一段电影的简介,由于字数比较多,所以字体设置的很小,行间距和段间距也很小,一大段文字挤在一起看起来很别扭,想要把行间距调大,结 ...

  6. iOS纯代码手动适配 分类: ios技术 2015-05-04 17:14 239人阅读 评论(0) 收藏

    首先说下让自己的程序支持iPhone6和6+,第一种使用官方提供的launch screen.xib,这个直接看官方文档即可,这里不再多述:第二种方法是和之前iPhone5的类似,比较简单,为iPho ...

  7. UI基础:视图控制器.屏幕旋转.MVC 分类: iOS学习-UI 2015-07-02 22:21 62人阅读 评论(0) 收藏

    UIViewController 视图控制器,继承自UIResponder,作用:管理视图并且响应事件 功能: 1.分担APPdelegate的工作 2.实现模块独立,能提高复用性 创建UIViewC ...

  8. UI基础:UI程序执行顺序(UIApplicationMain()函数),自定义视图 分类: iOS学习-UI 2015-07-02 22:09 68人阅读 评论(0) 收藏

    UI程序的一般执行顺序: 先进入main里面,执行函数UIApplicationMain(),通过该函数创建应用程序对象和指定其代理并实现监听,当执行函数UIApplicationMain()时还会做 ...

  9. C语言基础:枚举.宏 分类: iOS学习 c语言基础 2015-06-10 22:01 20人阅读 评论(0) 收藏

    枚举:一组有符号的整型常量,一 一列举所有的状态 枚举常和switch连用 enum week{ monday=1, tuesday, wednesday, thursday, friday, sat ...

随机推荐

  1. UVALive 2147 Push!!(队列实现DP)

    就我的理解来说这个题,本质上是一个DP题,不应该说是搜索,因为我的做法是把表格中所有的数据都找到,使用队列暴力来遍历出所有状态,因为题目中的数据范围小,所有耗时也小. 首先分析箱子是一个被动物体,人是 ...

  2. AngularJS 基础用法

    判断语句: <li ng-repeat=”person in persons”> <span ng-switch on=”person.sex”> <span ng-sw ...

  3. Struts的前世今身

    1.Struts1的运行原理 a.初始化:struts框架的总控制器ActionServlet是一个Servlet,它在web.xml中配置成自动启动的Servlet,在启动时总控制器会读取配置文件( ...

  4. Oracle Sql优化之Rownum的使用

    1.rownum:rownum是一个伪列,需要在数据取出来后,rownum才会有值,因此在分页查找时,需要进行嵌套查询. select sal,ename from (select rownum as ...

  5. PAT1006

    At the beginning of every day, the first person who signs in the computer room will unlock the door, ...

  6. 表单提交中记得form表单放到table外面

    帝国后台按栏目搜索文章时怎么都不生效  控制台查看原来是 栏目的select的值没有提交过去,原来由于form标签在table标签里面,导致js生成的<select>标签提交失败. 解决办 ...

  7. HTML的TextArea标记跟随文本内容自动设置高度

    js <textarea name="textarea" id="textarea" style='overflow-y: hidden;height:2 ...

  8. expdp.sh and impdp.sh

    ####expdp.sh ###### ------------- --   UAT   -- ------------- @D:\dba\change\UAT\eais\env\env_eaisua ...

  9. FileSystemXmlApplicationContext、ClassPathXmlApplicationContext和XmlWebApplicationContext简介

    今天在用Spring时遇到一个问题,提示找不到applicationContext.xml文件.原来是在加载这个文件时调用的方法不太合适,所以造成了程序找不到项目下的xml配置文件. 我们常用的加载c ...

  10. Cells Not Under Attack

    Cells Not Under Attack Vasya has the square chessboard of size n × n and m rooks. Initially the ches ...