-
上一篇已实现基本的UI,表情键盘及键盘位置的处理
- 接下来实现Socket连接
- 文字消息的互相发送
效果图
一.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)