iOS scoket 初探

学习iOS也有一段时间了。也在试着用iOS来写项目,感谢各路大神的帮助,就不一一@了。本文只是记载本人的学习过程。

                                                                           ---------------------学如逆水行舟不进则退。


1我也只是试一试,如有错误还请各位指出点评

越来越多的应用开始有了即时通讯的功能,我们就可以用scoket来实现


1.框架AsyncSocket


引入头文件

AsyncSocket.h


2.直接贴出代码了

//

//  RootViewController.h

//  socket测试一下感觉简单

//

//  Created by黄权浩 on 14-11-30.

//  Copyright (c) 2014黄权浩. All rights reserved.

//


#import <UIKit/UIKit.h>

//聊天

#import "AsyncSocket.h"


@interface RootViewController : UIViewController{

    

    AsyncSocket *client;

}


@property (nonatomic, retain) AsyncSocket *client;

@property (weak, nonatomic) IBOutlet UILabel *outputMsg;

@property (weak, nonatomic) IBOutlet UITextField *inputMsg;


- (int) connectServer:(NSString *)hostIP port:(int)hostPort;

- (void) showMessage:(NSString *) msg;

- (IBAction) sendMsg;

- (IBAction) reConnect;


@end



.m


//

//  RootViewController.m

//  socket测试一下感觉简单

//

//  Created by黄权浩 on 14-11-30.

//  Copyright (c) 2014黄权浩. All rights reserved.

//


#import "RootViewController.h"

//GCD

#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_PORT1 8080


@interface RootViewController ()


@end


@implementation RootViewController


@synthesize inputMsg, outputMsg;

@synthesize client;

/*********

 

 

哈哈。scoket

 }

*********/




// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

- (void)viewDidLoad {

    [super viewDidLoad];

    [self connectServer:HOST_IP port:HOST_PORT1];

    //监听读取

    

}




// 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(@"%ld %@", (long)[err code], [err localizedDescription]);

            

            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[@"Connection failed to host "

                                                            stringByAppendingString:hostIP]

                                                            message:[[[NSString alloc]initWithFormat:@"%ld",(long)[err code]] stringByAppendingString:[err localizedDescription]]

                                                           delegate:self

                                                  cancelButtonTitle:@"OK"

                                                  otherButtonTitles:nil];

            [alert show];

            //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_PORT1];

    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(@"%@",content);

    NSData *data = [content dataUsingEncoding:NSISOLatin1StringEncoding];

    [client writeData:data withTimeout:-1 tag:0];

    //继续监听读取

    [client readDataWithTimeout:-1 tag:0];

}


#pragma mark socket uitl

- (void) showMessage:(NSString *) msg{

    UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"Alert!"

                                                    message:msg

                                                   delegate:nil

                                          cancelButtonTitle:@"OK"

                                          otherButtonTitles:nil];

    [alert show];

}



#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];

    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;

    [client readDataWithTimeout:-1 tag:0];

}


@end


-----------------------------------日日精进 但求无愧-----------------------------------



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黄权浩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值