iphone使用开源代码Asyncsocket进行socket编程 之二

本文介绍如何使用AsyncSocket库在iOS平台上实现socket通信。提供了详细的代码示例,包括连接服务器、发送消息及错误处理等功能。

在iphone的平台下,要进行socket开发其实有很多种的方法,开源的库Asyncsocket,官方的CFSocket,还有BSD的socket。

下面是用开源的库Asyncsocket的例子:

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

 

AI-PPT 一键生成 PPT:用户输入主题关键词,AI-PPT 可快速生成完整 PPT,涵盖标题、正文、段落结构等,还支持对话式生成,用户可在 AI 交互窗口边查看边修改。 文档导入转 PPT:支持导入 Word、Excel、PDF 等多种格式文档,自动解析文档结构,将其转换为结构清晰、排版规范的 PPT,有保持原文和智能优化两种模式。 AI-PPT 对话 实时问答:用户上传 PPT 或 PPTX 文件后,可针对演示内容进行提问,AI 实时提供解答,帮助用户快速理解内容。 多角度内容分析:对 PPT 内容进行多角度分析,提供全面视野,帮助用户更好地把握内容结构和重点。 多语言对话支持:支持多语言对话,打破语言障碍,方便不同语言背景的用户使用。 AI - 绘图 文生图:用户输入文字描述,即可生成符合语义的不同风格图像,如油画、水彩、中国画等,支持中英文双语输入。 图生图:用户上传图片并输入描述,AI - 绘图能够根据参考图和描述生成新的风格化图像,适用于需要特定风格或元素的创作需求。 图像编辑:提供如 AI 超清、AI 扩图、AI 无痕消除等功能,用户可以上传图片进行细节修改和优化,提升图片质量。 AI - 文稿 文案生成:能够根据用户需求生成多种类型的文章,如市场营销文案、技术文档、内部沟通内容等,提升文案质量和创作效率。 文章润色:对已有文章进行改善和优化,包括语言表达、逻辑连贯性、内容流畅度等方面,使文章更符合用户期望和风格。 文章续写:AI 技术理解文本语境,为用户提供新的想法、补充资料或更深层次的见解,帮助用户丰富文档内容。 AI - 医生 智能健康咨询:包括症状自查,用户输入不适症状,AI 结合病史等信息提供疾病可能性分析与初步建议;用药指导,支持查询药品适应症、禁忌症等,并预警潜在冲突;中医辨证,提供体质辨识与调理建议。 医学报告解读:用户上传体检报告
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值