博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
iOS AsynSocket实现即时通讯
阅读量:4290 次
发布时间:2019-05-27

本文共 4137 字,大约阅读时间需要 13 分钟。

#import "ViewController.h"

#import "GCDAsyncSocket.h"

@interface ViewController ()<UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate,GCDAsyncSocketDelegate>{

    

    GCDAsyncSocket *_socket;

}

@property (weak, nonatomic) IBOutletNSLayoutConstraint *inputViewConstraint;

@property (weak, nonatomic) IBOutletUITableView *tableView;

@property (nonatomic,strong)NSMutableArray *chatMsgs;//聊天消息数组

@end

@implementation ViewController

-(NSMutableArray *)chatMsgs{

    if (!_chatMsgs) {

        _chatMsgs = [NSMutableArrayarray];

    }

    

    return_chatMsgs;

}

- (void)viewDidLoad {

    [superviewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

  

    

    // 2.收发数据

    // 做一个聊天

    // 1.用户登录

    // 2.收发数据

    

    // 监听键盘

    [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(kbFrmWillChange:)name:UIKeyboardWillChangeFrameNotificationobject:nil];

}

-(void)kbFrmWillChange:(NSNotification *)noti{

    NSLog(@"%@",noti.userInfo);

    

    // 获取窗口的高度

    

    CGFloat windowH = [UIScreenmainScreen].bounds.size.height;

    

   

    

    // 键盘结束的Frm

    CGRect kbEndFrm = [noti.userInfo[UIKeyboardFrameEndUserInfoKey]CGRectValue];

     // 获取键盘结束的y

    CGFloat kbEndY = kbEndFrm.origin.y;

    

    

    self.inputViewConstraint.constant = windowH - kbEndY;

}

- (IBAction)connectToHost:(id)sender {

    // 1.建立连接

    NSString *host = @"127.0.0.1";

    int port = 12345;

    

    // 创建一个Socket对象

    _socket = [[GCDAsyncSocketalloc]initWithDelegate:selfdelegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)];

    

    // 连接

    NSError *error = nil;

    [_socket connectToHost:hostonPort:porterror:&error];

    if (error) {

        NSLog(@"%@",error);

    }

}

#pragma mark -AsyncSocket的代理

#pragma mark 连接主机成功

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

    NSLog(@"连接主机成功");

}

#pragma mark 与主机断开连接

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

    if(err){

        NSLog(@"断开连接 %@",err);

    }

}

- (IBAction)loginBtnClick:(id)sender {

    

    // 登录

    // 发送用户名和密码

    // 在这里做的时候,只发用户名,密码就不用发送

    

    // 如果要登录,发送的数据格式为 "iam:zhangsan";

    // 如果要发送聊天消息,数据格式为 "msg:did you have dinner";

    

    //登录的指令

    NSString *loginStr = @"iam:zhangsan";

    

    //Str转成NSData

    NSData *data = [loginStrdataUsingEncoding:NSUTF8StringEncoding];

    

    //[_outputStream write:data.bytes maxLength:data.length];

    // 发送登录指令给服务

    [_socketwriteData:datawithTimeout:-1tag:101];

}

#pragma mark 数据成功发送到服务器

-(void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag{

    NSLog(@"数据成功发送到服务器");

    //数据发送成功后,自己调用一下读取数据的方法,接着_socket才会调用下面的代理方法

    [_socketreadDataWithTimeout:-1tag:tag];

}

#pragma mark 服务器有数据,会调用这个方法

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

    // 从服务器接收到的数据

    NSString *recStr =  [[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];

    

    NSLog(@"%@ %ld %@",[NSThreadcurrentThread],tag, recStr);

    

    if (tag == 102) {

//聊天返回的数据

        // 刷新表格

        [self reloadDataWithText:recStr];

    }

//    }else if(tag == 101 ){//登录返回数据,不应该把数据添加到表格里

//

//

//    }

   

}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{

    

    NSString *text = textField.text;

    

    NSLog(@"%@",text);

    // 聊天信息

    NSString *msgStr = [NSStringstringWithFormat:@"msg:%@",text];

    

    //Str转成NSData

    NSData *data = [msgStrdataUsingEncoding:NSUTF8StringEncoding];

    

    // 刷新表格

    [selfreloadDataWithText:msgStr];

    

    // 发送数据

    [_socketwriteData:datawithTimeout:-1tag:102];

    

    // 发送完数据,清空textField

    textField.text = nil;

    

    return YES;

}

-(void)reloadDataWithText:(NSString *)text{

    [self.chatMsgsaddObject:text];

    

    // UI刷新要主线程

    dispatch_async(dispatch_get_main_queue(), ^{

        [self.tableViewreloadData];

        

        // 数据多,应该往上滚动

        NSIndexPath *lastPath = [NSIndexPathindexPathForRow:self.chatMsgs.count -1 inSection:0];

        [self.tableViewscrollToRowAtIndexPath:lastPathatScrollPosition:UITableViewScrollPositionBottomanimated:YES];

    });

  

}

#pragma mark 表格的数据源

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.chatMsgs.count;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *ID =@"Cell";

    UITableViewCell *cell = [tableViewdequeueReusableCellWithIdentifier:ID];

   

    cell.textLabel.text =self.chatMsgs[indexPath.row];

    

    return cell;

}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{

    [self.viewendEditing:YES];

}

@end

转载地址:http://mhlgi.baihongyu.com/

你可能感兴趣的文章
网络_断点续传.断点下载
查看>>
网络_Xutils
查看>>
网络_多线程下载
查看>>
网络_httpClient
查看>>
网络_HttpURLConnection_原始类
查看>>
网络_OKHttp
查看>>
android_事件分发机制_几行代码直接通晓
查看>>
图片_OOM_OutOfMemory
查看>>
技术学习_经验分享
查看>>
android中常见的设计模式有哪些?
查看>>
ViewDragHelper_v4的滑动视图帮助类_解释和代码
查看>>
即时通讯技术- 推送技术协议方案
查看>>
vitamio简介.java
查看>>
ActiveMQ 实现负载均衡+高可用部署方案
查看>>
《搜索和推荐中的深度匹配》——2.5 延伸阅读
查看>>
解读:阿里文娱搜索算法实践与思考
查看>>
基于位置的点击模型
查看>>
链表操作算法题合集
查看>>
Crackme3 破解教程
查看>>
奖学金评比系统(数据库系统设计版)
查看>>