Socket客户端(三)

1、将GCDAsyncSocket框架导入项目中
2、代码实现如下:

#import <Foundation/Foundation.h>
@interface MessageModel : NSObject
@property (nonatomic, strong) NSString *type;
@property (nonatomic, strong) NSString *context;
@end
#import <UIKit/UIKit.h>
@interface MessageCell : UITableViewCell
@property (nonatomic, strong) UILabel *message;
@end
#import "MessageCell.h"
@implementation MessageCell
-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if ([super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.message = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, [UIScreen mainScreen].bounds.size.width - 40, 20)];
        [self.contentView addSubview:self.message];
    }
    return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    // Configure the view for the selected state
}
#import "ViewController.h"
#import "GCDAsyncSocket.h"
#import "MessageCell.h"
#import "MessageModel.h"

#define kWidth self.view.frame.size.width
#define kHeight self.view.frame.size.height


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

@property (nonatomic, strong) GCDAsyncSocket *socket;

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UITextField *textFiled;
@property (nonatomic, strong) UIButton *sendBtn;

@property (nonatomic, strong) NSMutableArray *dataSource;


@end

@implementation ViewController

-(NSMutableArray *)dataSource{
    if (!_dataSource) {
        self.dataSource = [NSMutableArray array];
    }
    return _dataSource;
}


- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0,kWidth ,kHeight - 40) style:UITableViewStyleGrouped];
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];


    self.textFiled = [[UITextField alloc] initWithFrame:CGRectMake(20, kHeight - 40, kWidth - 100, 30)];
    self.textFiled.backgroundColor = [UIColor grayColor];
    [self.view addSubview:self.textFiled];

    self.sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.sendBtn.frame = CGRectMake(kWidth - 100, kHeight - 40, 80, 30);
    [self.sendBtn setTitle:@"发送" forState:UIControlStateNormal];
    self.sendBtn.backgroundColor = [UIColor orangeColor];
    [self.sendBtn addTarget:self action:@selector(handleSenderAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.sendBtn];



    //连接到聊天服务器
    GCDAsyncSocket *socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_global_queue(0, 0)];
    [socket connectToHost:@"192.168.0.187" onPort:5239 error:nil];
    self.socket = socket;
    [self.tableView registerClass:[MessageCell class] forCellReuseIdentifier:@"cell"];
}

-(void)handleSenderAction{
    if (self.textFiled.text.length >0) {
        [self.socket writeData:[self.textFiled.text dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
        //添加到数据源
        MessageModel *model = [[MessageModel alloc] init];
        model.type = @"s";
        model.context = [NSString stringWithFormat:@"ME::%@",self.textFiled.text];
        [self.dataSource addObject:model];
        //刷新
        [self.tableView reloadData];
    }
    self.textFiled.text = @"";
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}

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

    MessageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    MessageModel *mmodel = self.dataSource[indexPath.row];
    cell.message.text = mmodel.context;
    if ([mmodel.type isEqualToString:@"r"]) {
        cell.message.textAlignment = NSTextAlignmentLeft;
    }else{
        cell.message.textAlignment = NSTextAlignmentRight;
    }
    return cell;
}

-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
    //1、读取数据
    NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@",string);
    //2、添加到数据源

    MessageModel *model = [[MessageModel alloc] init];
    model.type = @"r";
    model.context = [NSString stringWithFormat:@"Other::%@",string];
    [self.dataSource addObject:model];
    //3、刷新数据
    [[NSOperationQueue mainQueue]addOperationWithBlock:^{
        [self.tableView reloadData];
    }];
    //4、每次接受完数据,都要再次监听数据
    [sock readDataWithTimeout:-1 tag:0];
}

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

    NSLog(@"连接主机成功");
    //监听数据
    [self.socket readDataWithTimeout:-1 tag:0];
}

-(void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err{
    NSLog(@"连接主机失败%@",err);
}
@end

3、连接主机
这里写图片描述
4、不同客户端之间互相发送信息
这里写图片描述
这里写图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值