局域网内端到端的聊天项目(三)

  • 上一篇已实现基本的UI,表情键盘及键盘位置的处理
  • 接下来实现Socket连接
  • 文字消息的互相发送
效果图
IMG_2426.GIF
IMG_0144.GIF

一.Socket工具类

建立消息模型 (ChatMessageModel) 包含对应的消息类型 / 名称 / 大小 等属性
#import <Foundation/Foundation.h>

static CGFloat const messageLabelForHeadLeftMargin = 15.0;
static CGFloat const messageLabelForHeadRightMargin = 8.0;

typedef NS_ENUM(int,ChatMessageType) {
 ChatMessageText     = 0,
 ChatMessageImage    = 1,
 ChatMessageVideo    = 2,
 ChatMessageAudio    = 3,
 ChatMessageLoaction = 4
};

@interface ChatMessageModel : NSObject
/// userName
@property (nonatomic, copy) NSString *userName;
/// userIcon
@property (nonatomic, copy) NSString *iconUrl;
/// 消息类型
@property (nonatomic, assign) int chatMessageType;
/// 消息内容 文字
@property (nonatomic, copy) NSString *messageContent;
/// 富文本消息内容
@property (nonatomic, copy) NSMutableAttributedString *messageContentAttributed;
/// PHAsset 媒体资源
@property (nonatomic, strong) id asset;
/// 媒体消息本地保存地址
@property (nonatomic, copy) NSURL *mediaMessageUrl;
/// 是否来至于自己
@property (nonatomic, assign) BOOL isFormMe;

/*************************** 传输相关 *****************************/
/// userName
@property (nonatomic, copy) NSString *fileName;
/// sendTag
@property (nonatomic, assign) NSInteger sendTag;
/// 文件总大小
@property (nonatomic, assign) NSInteger fileSize;

/// 文件已上传大小
@property (nonatomic, assign) NSInteger upSize;
/// 是否正在上传中
@property (nonatomic, assign) BOOL isSending;
/// 当前文件是否已经全部传输完毕
@property (nonatomic, assign) BOOL isSendFinish;

/// 已接受的文件大小
@property (nonatomic, assign) NSInteger acceptSize;
/// 开始接受
@property (nonatomic, assign) BOOL beginAccept;
/// 接受完成
@property (nonatomic, assign) BOOL finishAccept;
/// 当前文件保存在本地的路径 <接收到文件>
@property (nonatomic, copy) NSString *acceptFilePath;
/// 是否在等待接收 <图片 / 视频 / 音频> 类型
@property (nonatomic, assign) BOOL isWaitAcceptFile;

/*************************** UI相关 *****************************/
/// 消息宽度
@property (nonatomic, assign) CGFloat messageW;
/// 消息高度
@property (nonatomic, assign) CGFloat messageH;
/// cell高度
@property (nonatomic, assign) CGFloat cellH;
@end
建立Socket管理类 (SocketManager)
  • 端口的监听
  • 建立连接
  • 消息的发送
  • 消息发送中/接收中 消息发送/接收完成的代理回调
SocketManager.h
#import <Foundation/Foundation.h>
#import "ChatMessageModel.h"
@class SocketManager;

@protocol SocketManagerDelegate <NSObject>
// 正在上传的文件回调
- (void)socketManager:(SocketManager *)manager  itemUpingrefresh:(ChatMessageModel *)upingItem;
// 文件上传完毕的回调
- (void)socketManager:(SocketManager *)manager  itemUpFinishrefresh:(ChatMessageModel *)finishItem;
// 正在接受的文件回调
- (void)socketManager:(SocketManager *)manager  itemAcceptingrefresh:(ChatMessageModel *)acceptingItem;

@end

@interface SocketManager : NSObject
/// delegate
@property (nonatomic, weak) id <SocketManagerDelegate> delegate;
/// 保存数据的主地址
@property (nonatomic, copy)  NSString *dataSavePath;

+ (instancetype)shareSockManager;
/// 监听端口
- (BOOL)startListenPort:(uint16_t)prot;
/// 连接
- (BOOL)connentHost:(NSString *)host prot:(uint16_t)port;
/// 发送数据
- (void)sendMessageWithItem:(ChatMessageModel *)item;
@end
SocketManager.m
@interface SocketManager()
/// socket
@property (nonatomic, strong) GCDAsyncSocket *tcpSocketManager;
/// 客户端socket集合
@property (nonatomic, strong) NSMutableArray *clientSocketArray;
/// 当前正在传送的item
@property (nonatomic, strong) ChatMessageModel *currentSendItem;
/// 当前传输的下标值
@property (nonatomic, assign) NSInteger currentSendTag;
/// 当前接收到的item
@property (nonatomic, strong) ChatMessageModel *acceptItem;
/// 输出流
@property (nonatomic, strong) NSOutputStream *outputStream;
@end
端口的监听
- (BOOL)startListenPort:(uint16_t)prot{
    if (prot <= 0) {
        NSAssert(prot > 0, @"prot must be more zero");
    }
    if (!self.tcpSocketManager) {
        self.tcpSocketManager = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    }
    [self.tcpSocketManager disconnect];
    
    NSError *error = nil;
    BOOL result = [self.tcpSocketManager acceptOnPort:prot error:&error];
    if (result && !error) {
        return YES;
    }else{
        return NO;
    }
}
建立连接
/// 连接
- (BOOL)connentHost:(NSString *)host prot:(uint16_t)port{
    if (host==nil || host.length <= 0) {
        NSAssert(host != nil, @"host must be not nil");
    }
    [self.tcpSocketManager disconnect];
    if (self.tcpSocketManager == nil) {
        self.tcpSocketManager = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    }
    NSError *connectError = nil;
    [self.tcpSocketManager connectToHost:host onPort:port error:&connectError];
    if (connectError) {
        return NO;
    }
    // 可读取服务端数据
    [self.tcpSocketManager readDataWithTimeout:-1 tag:0];
    return YES;
}
对消息内容进行包装发送(这篇只对文字消息处理 图片/视频会在下一篇进行处理)
/// 发送数据 
- (void)sendMessageWithItem:(ChatMessageModel *)item{
    self.currentSendItem = item;
    if (item.chatMessageType == ChatMessageText) {
        NSData *textData = [self creationMessageDataWithItem:item];
        [self writeMediaMessageWithData:textData];
    }else if (item.chatMessageType == ChatMessageImage || item.chatMessageType == ChatMessageVideo){
       // 下一篇进行处理
    }
}

// 创建消息体
- (NSData *)creationMessageDataWithItem:(ChatMessageModel *)item{
    NSMutableDictionary *messageData = [NSMutableDictionary dictionary];
    messageData[@"fileName"] = item.fileName;
    messageData[@"userName"] = item.userName;
    messageData[@"chatMessageType"] = [NSNumber numberWithInt:item.chatMessageType];
    messageData[@"fileSize"] = [NSNumber numberWithInteger:item.fileSize];
    if (item.chatMessageType == ChatMessageText) {
        messageData[@"messageContent"] = item.messageContent;
    }
    NSString *bodStr = [NSString hj_dicToJsonStr:messageData];
    return [bodStr dataUsingEncoding:NSUTF8StringEncoding];
}
GCDSocketDelegate 代理回调
/// 新的客户端连接上
- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket{
    if (!self.clientSocketArray) {
        self.clientSocketArray = [NSMutableArray array];
    }else{
        // 目前只做点对点的聊天
        [self.clientSocketArray removeAllObjects];
    }
    [self.clientSocketArray addObject:newSocket];
    [newSocket readDataWithTimeout:- 1 tag:0];
}

/// 客户端连接到的
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port{
    NSLog(@"%s",__func__);
}

/// 接收到消息
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
    NSString *readStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSDictionary *readDic = [readStr hj_jsonStringToDic];
    
    if ([readDic isKindOfClass:[NSDictionary class]]) {
        self.acceptItem = [ChatMessageModel mj_objectWithKeyValues:readDic];
        self.acceptItem.isFormMe = NO;
        // 接收到非字符串类型 (预留 对图片 / 视频 / 音频等的处理)
        self.acceptItem.isWaitAcceptFile = self.acceptItem.chatMessageType != ChatMessageText ? YES : NO;
    }
   
    if (self.acceptItem.isWaitAcceptFile) {
        // 此处对音视频文件进行处理
    }else{
        self.acceptItem.finishAccept = YES;
    }
    // 回调出去
    if ([self.delegate respondsToSelector:@selector(socketManager:itemAcceptingrefresh:)]) {
        [self.delegate socketManager:self itemAcceptingrefresh:self.acceptItem];
    }
    
    [sock readDataWithTimeout:- 1 tag:0];
    
}

// 文件传输完毕后的回调
- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag{
    MYLog(@"%s \n tag = %ld",__func__,tag);
    if ([self.delegate respondsToSelector:@selector(socketManager:itemUpFinishrefresh:)]) {
        [self.delegate socketManager:self itemUpFinishrefresh:self.currentSendItem];
    }
    [self.tcpSocketManager setAutoDisconnectOnClosedReadStream:YES];
    
}

// 分段传输完成后的 回调
- (void)socket:(GCDAsyncSocket *)sock didWritePartialDataOfLength:(NSUInteger)partialLength tag:(long)tag {
    MYLog(@"%lu--tag = %zd",partialLength,tag);
    self.currentSendItem.upSize += partialLength;
    if ([self.delegate respondsToSelector:@selector(socketManager:itemUpingrefresh:)] && (tag==self.currentSendItem.sendTag)) {
        self.currentSendItem.isSending = YES;
        [self.delegate socketManager:self itemUpingrefresh:self.currentSendItem];
    }
}

二.文字消息的相互发送

  • 键盘工具类的发送消息的回调
  • 发送完成后SockeManager的代理回调
  • 接受到消息时SockeManager的代理回调
点击键盘发送按钮的回调处理
#pragma mark - ESKeyBoardToolViewDelegate
- (void)ESKeyBoardToolViewSendButtonDidClick:(ESKeyBoardToolView *)view message:(NSString *)message{
    ChatMessageModel *messageM = [ChatMessageModel new];
    messageM.isFormMe = YES;
    messageM.userName = [UIDevice currentDevice].name;
    messageM.messageContent = message;
    messageM.chatMessageType = ChatMessageText;
    [self sendMessageWithItem:messageM];
}

- (void)sendMessageWithItem:(ChatMessageModel *)item{
    SocketManager *manager = [SocketManager shareSockManager];
    [manager sendMessageWithItem:item];
}
发送/接收完成后SockeManager的代理回调
- (void)socketManager:(SocketManager *)manager  itemUpFinishrefresh:(ChatMessageModel *)finishItem{
    [self.messageItems addObject:finishItem];
    [self.tableView reloadData];
    [self scrollToLastCell];
}

- (void)socketManager:(SocketManager *)manager  itemAcceptingrefresh:(ChatMessageModel *)acceptingItem{
    if (acceptingItem.finishAccept) {
        [self.messageItems addObject:acceptingItem];
        [self.tableView reloadData];
        [self scrollToLastCell];
    }
}
scrollToLastCell 方法 在 reloadData 方法后调用 需在主队列中进行计算高度
- (void)scrollToLastCell{
    if (self.messageItems.count <= 0) {
        return;
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        CGFloat contentH = self.tableView.contentSize.height;
        CGFloat showH = self.tableView.hj_height - (self.view.hj_height - self.keyBoardToolView.y - TitleViewHeight);
        CGFloat needOffsetY =  (contentH - showH);
        if (needOffsetY > 0) {
            [self.tableView setContentOffset:CGPointMake(self.tableView.contentOffset.x, needOffsetY) animated:YES];
        }
    });
}
随便添加了一个聊天背景图...(self.tableView.backgroundView)
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容