iOS scoket 再探。换成了GCDAsyncSocket,并且实现了双方聊天

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

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


1.这次换成了GCDAsyncSocket框架,先看下完成图吧



另一方




贴上代码吧,有注释估计不难

客户

.h

//

//  RootViewController.h

//  hqhtestsocket

//

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

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

//


#import <UIKit/UIKit.h>

#import "GCDAsyncSocket.h"


@interface RootViewController : UIViewController<GCDAsyncSocketDelegate,UITextFieldDelegate>

{

    GCDAsyncSocket *socket;

    

    //发送消息按钮

    UIButton *sendMg2;

    

    //发送消息

    //键盘弹起来的通知变化

    UIView *TestV;

    

    UITextField *textView;

}



@property(strong)  GCDAsyncSocket *socket;


//IP

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


//端口

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


//连接服务器

- (IBAction)lianjie:(id)sender;


//展示消息

@property (weak, nonatomic) IBOutlet UITextView *showMg;



.m

//

//  RootViewController.m

//  hqhtestsocket

//

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

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

//


#import "RootViewController.h"


@interface RootViewController ()


@end


@implementation RootViewController

@synthesize socket;

- (void)viewDidLoad {

    [super viewDidLoad];

    

    //注册键盘通知来让消息框弹起

    [self registerForKeyboardNotifications];

    

    //搭建聊天的页面

    TestV = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height-50, 320, 50)];

    //打开交互

    TestV.userInteractionEnabled = YES;

    TestV.backgroundColor = [UIColor grayColor];

    

    //搞个UITextView

    textView = [[UITextField alloc] initWithFrame:CGRectMake(10, 5, 230, 40)];

    textView.delegate = self;

    textView.borderStyle = UITextBorderStyleRoundedRect;

    

    //搞个发送消息的按钮

    UIButton *sendMg = [UIButton buttonWithType:UIButtonTypeCustom];

    [sendMg setTitle:@"Send" forState:UIControlStateNormal];

    [sendMg setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

    [sendMg addTarget:self action:@selector(sendMG) forControlEvents:UIControlEventTouchUpInside];

    [sendMg setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];

    sendMg.frame = CGRectMake(250, 5, 60, 40);

    [TestV addSubview:sendMg];

    [TestV addSubview:textView];

    [self.view addSubview:TestV];


    

}


//注册键盘弹起来的通知

- (void)registerForKeyboardNotifications

{

    //监听键盘抬起

//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showContentViewPoint:) name:UIKeyboardWillShowNotification object:nil];

    

    //监听键盘收回

//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hiddenContentViewPoint:) name:UIKeyboardWillShowNotification object:nil];

    

    //监听键盘改变

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeContentViewPoint:) name:UIKeyboardWillShowNotification object:nil];

}


//键盘的通知

- (void)changeContentViewPoint:(NSNotification *)notification{

    NSDictionary *userInfo = [notification userInfo];

    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];

    CGFloat keyBoardEndY = value.CGRectValue.origin.y;

    // 得到键盘弹出后的键盘视图所在y坐标

    NSNumber *duration = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];    NSNumber *curve = [userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];

    // 添加移动动画,使视图跟随键盘移动

    [UIView animateWithDuration:duration.doubleValue animations:^{

        [UIView setAnimationBeginsFromCurrentState:YES];

        [UIView setAnimationCurve:[curve intValue]];

        TestV.center = CGPointMake(TestV.center.x, keyBoardEndY - TestV.bounds.size.height/2.0);

        // keyBoardEndY的坐标包括了状态栏的高度,要减去

    }

     ];

    

}


//收起键盘

- (void)dsms{

    [textView resignFirstResponder];

    [_duankou resignFirstResponder];

    [_ip resignFirstResponder];

    //做动画过渡

    [UIView beginAnimations:nil context:nil];

    [UIView setAnimationDuration:0.3];

    [UIView setAnimationDelegate:self];

    TestV.frame = CGRectMake(0, self.view.bounds.size.height-50, 320, 50);

    [UIView commitAnimations];

}


- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


//将消息显示换行

-(void)addText:(NSString *)str

{

    _showMg.text = [_showMg.text stringByAppendingFormat:@"%@\n",str];

}


//连接服务器

- (IBAction)lianjie:(id)sender {

    

    socket = [[GCDAsyncSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_main_queue()];

    //socket.delegate = self;

    NSError *err = nil;

    if(![socket connectToHost:_ip.text onPort:[_duankou.text intValue] error:&err])

    {

        [self addText:err.description];

    }else

    {

        NSLog(@"ok");

        [self addText:@"打开端口"];

    }

    

    [self dsms];

}


//连接到的地方

-(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port

{

    [self addText:[NSString stringWithFormat:@"连接到:%@",host]];

    [socket readDataWithTimeout:-1 tag:0];

}



- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err

{

    

}


-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag

{

    NSString *newMessage = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    

    [self addText:[NSString stringWithFormat:@"服务器:%@:%@",sock.connectedHost,newMessage]];

    [socket readDataWithTimeout:-1 tag:0];

}


//发送消息

- (void)sendMG{

    //做动画过渡

    [UIView beginAnimations:nil context:nil];

    [UIView setAnimationDuration:0.3];

    [UIView setAnimationDelegate:self];

    TestV.frame = CGRectMake(0, self.view.bounds.size.height-50, 320, 50);

    [UIView commitAnimations];

    

    [socket writeData:[textView.text dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];

    

    [self addText:[NSString stringWithFormat:@":%@",textView.text]];

    [textView resignFirstResponder];

    [socket readDataWithTimeout:-1 tag:0];

}


@end



nib图:


另一端
.h

//

//  RootViewController.h

//  hqhtestsocket

//

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

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

//


#import <UIKit/UIKit.h>

#import "GCDAsyncSocket.h"


@interface RootViewController : UIViewController<GCDAsyncSocketDelegate,UITextFieldDelegate>

{

    GCDAsyncSocket *socket;

    

    //发送消息按钮

    UIButton *sendMg2;

    

    //发送消息

    //键盘弹起来的通知变化

    UIView *TestV;

    

    UITextField *textView;

}



@property(strong)  GCDAsyncSocket *socket;


//端口

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


//连接服务器

- (IBAction)lianjie:(id)sender;


//展示消息

@property (weak, nonatomic) IBOutlet UITextView *showMg;




@end



.m

//

//  RootViewController.m

//  hqhtestsocket

//

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

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

//


#import "RootViewController.h"


@interface RootViewController ()


@end


@implementation RootViewController

@synthesize socket;

- (void)viewDidLoad {

    [super viewDidLoad];

    

    //注册键盘通知来让消息框弹起

    [self registerForKeyboardNotifications];

    

    //默认端口号

    _duankou.text = @"54321";

    

    //搭建聊天的页面

    TestV = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height-50, 320, 50)];

    //打开交互

    TestV.userInteractionEnabled = YES;

    TestV.backgroundColor = [UIColor grayColor];

    

    //搞个UITextView

    textView = [[UITextField alloc] initWithFrame:CGRectMake(10, 5, 230, 40)];

    textView.delegate = self;

    textView.borderStyle = UITextBorderStyleRoundedRect;

    

    //搞个发送消息的按钮

    UIButton *sendMg = [UIButton buttonWithType:UIButtonTypeCustom];

    [sendMg setTitle:@"Send" forState:UIControlStateNormal];

    [sendMg setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

    [sendMg addTarget:self action:@selector(sendMG) forControlEvents:UIControlEventTouchUpInside];

    [sendMg setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];

    sendMg.frame = CGRectMake(250, 5, 60, 40);

    [TestV addSubview:sendMg];

    [TestV addSubview:textView];

    [self.view addSubview:TestV];


    

}


- (void)socket:(GCDAsyncSocket *)sender didAcceptNewSocket:(GCDAsyncSocket *)newSocket

{

    // The "sender" parameter is the listenSocket we created.

    // The "newSocket" is a new instance of GCDAsyncSocket.

    // It represents the accepted incoming client connection.

    

    // Do server stuff with newSocket...

    [self addText:[NSString stringWithFormat:@"建立与%@的连接",newSocket.connectedHost]];

    

    socket = newSocket;

    socket.delegate = self;

    [socket readDataWithTimeout:-1 tag:0];

}


-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag

{

    NSString *receive = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    [self addText:[NSString stringWithFormat:@"%@:%@",sock.connectedHost,receive]];

    

    NSString *reply = [NSString stringWithFormat:@"收到:%@",receive];

    

    [socket writeData:[reply dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];

    [socket readDataWithTimeout:-1 tag:0];

}



//注册键盘弹起来的通知

- (void)registerForKeyboardNotifications

{

    //监听键盘抬起

//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showContentViewPoint:) name:UIKeyboardWillShowNotification object:nil];

    

    //监听键盘收回

//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hiddenContentViewPoint:) name:UIKeyboardWillShowNotification object:nil];

    

    //监听键盘改变

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeContentViewPoint:) name:UIKeyboardWillShowNotification object:nil];

}


//键盘的通知

- (void)changeContentViewPoint:(NSNotification *)notification{

    NSDictionary *userInfo = [notification userInfo];

    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];

    CGFloat keyBoardEndY = value.CGRectValue.origin.y;

    // 得到键盘弹出后的键盘视图所在y坐标

    NSNumber *duration = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];    NSNumber *curve = [userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];

    // 添加移动动画,使视图跟随键盘移动

    [UIView animateWithDuration:duration.doubleValue animations:^{

        [UIView setAnimationBeginsFromCurrentState:YES];

        [UIView setAnimationCurve:[curve intValue]];

        TestV.center = CGPointMake(TestV.center.x, keyBoardEndY - TestV.bounds.size.height/2.0);

        // keyBoardEndY的坐标包括了状态栏的高度,要减去

    }

     ];

    

}


//收起键盘

- (void)dsms{

    [textView resignFirstResponder];

    [_duankou resignFirstResponder];

    //做动画过渡

    [UIView beginAnimations:nil context:nil];

    [UIView setAnimationDuration:0.3];

    [UIView setAnimationDelegate:self];

    TestV.frame = CGRectMake(0, self.view.bounds.size.height-50, 320, 50);

    [UIView commitAnimations];

}


- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


//将消息显示换行

-(void)addText:(NSString *)str

{

    _showMg.text = [_showMg.text stringByAppendingFormat:@"%@\n",str];

}


//监听

- (IBAction)lianjie:(id)sender {

    NSLog(@"listen");

    

    socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];

    NSError *err = nil;

    if(![socket acceptOnPort:[_duankou.text integerValue] error:&err])

    {

        [self addText:err.description];

    }else

    {

        [self addText:[NSString stringWithFormat:@"开始监听%d端口.",_duankou.text.integerValue]];

    }


}


//连接到的地方

-(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port

{

    [self addText:[NSString stringWithFormat:@"连接到:%@",host]];

    [socket readDataWithTimeout:-1 tag:0];

}



- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err

{

    

}



//发送消息

- (void)sendMG{

    //做动画过渡

    [UIView beginAnimations:nil context:nil];

    [UIView setAnimationDuration:0.3];

    [UIView setAnimationDelegate:self];

    TestV.frame = CGRectMake(0, self.view.bounds.size.height-50, 320, 50);

    [UIView commitAnimations];

    [textView resignFirstResponder];

    [socket writeData:[textView.text dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];

    

    [self addText:[NSString stringWithFormat:@":%@",textView.text]];

    [textView resignFirstResponder];

    [socket readDataWithTimeout:-1 tag:0];

}

@end


nib 图


实现了相互的聊天
--------------------------------------------日日精进   但求无愧-------------------------------------------
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

黄权浩

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

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

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

打赏作者

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

抵扣说明:

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

余额充值