- 上一篇已實現(xiàn)基本的UI,表情鍵盤及鍵盤位置的處理
- 接下來實現(xiàn)Socket連接
- 文字消息的互相發(fā)送
效果圖
IMG_2426.GIF
IMG_0144.GIF
IMG_2426.GIF
IMG_0144.GIF
一.Socket工具類
建立消息模型 (ChatMessageModel) 包含對應(yīng)的消息類型 / 名稱 / 大小 等屬性
#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;
/// 消息內(nèi)容 文字
@property (nonatomic, copy) NSString *messageContent;
/// 富文本消息內(nèi)容
@property (nonatomic, copy) NSMutableAttributedString *messageContentAttributed;
/// PHAsset 媒體資源
@property (nonatomic, strong) id asset;
/// 媒體消息本地保存地址
@property (nonatomic, copy) NSURL *mediaMessageUrl;
/// 是否來至于自己
@property (nonatomic, assign) BOOL isFormMe;
/*************************** 傳輸相關(guān) *****************************/
/// 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;
/// 當(dāng)前文件是否已經(jīng)全部傳輸完畢
@property (nonatomic, assign) BOOL isSendFinish;
/// 已接受的文件大小
@property (nonatomic, assign) NSInteger acceptSize;
/// 開始接受
@property (nonatomic, assign) BOOL beginAccept;
/// 接受完成
@property (nonatomic, assign) BOOL finishAccept;
/// 當(dāng)前文件保存在本地的路徑 <接收到文件>
@property (nonatomic, copy) NSString *acceptFilePath;
/// 是否在等待接收 <圖片 / 視頻 / 音頻> 類型
@property (nonatomic, assign) BOOL isWaitAcceptFile;
/*************************** UI相關(guān) *****************************/
/// 消息寬度
@property (nonatomic, assign) CGFloat messageW;
/// 消息高度
@property (nonatomic, assign) CGFloat messageH;
/// cell高度
@property (nonatomic, assign) CGFloat cellH;
@end
建立Socket管理類 (SocketManager)
- 端口的監(jiān)聽
- 建立連接
- 消息的發(fā)送
- 消息發(fā)送中/接收中 消息發(fā)送/接收完成的代理回調(diào)
SocketManager.h
#import <Foundation/Foundation.h>
#import "ChatMessageModel.h"
@class SocketManager;
@protocol SocketManagerDelegate <NSObject>
// 正在上傳的文件回調(diào)
- (void)socketManager:(SocketManager *)manager itemUpingrefresh:(ChatMessageModel *)upingItem;
// 文件上傳完畢的回調(diào)
- (void)socketManager:(SocketManager *)manager itemUpFinishrefresh:(ChatMessageModel *)finishItem;
// 正在接受的文件回調(diào)
- (void)socketManager:(SocketManager *)manager itemAcceptingrefresh:(ChatMessageModel *)acceptingItem;
@end
@interface SocketManager : NSObject
/// delegate
@property (nonatomic, weak) id <SocketManagerDelegate> delegate;
/// 保存數(shù)據(jù)的主地址
@property (nonatomic, copy) NSString *dataSavePath;
+ (instancetype)shareSockManager;
/// 監(jiān)聽端口
- (BOOL)startListenPort:(uint16_t)prot;
/// 連接
- (BOOL)connentHost:(NSString *)host prot:(uint16_t)port;
/// 發(fā)送數(shù)據(jù)
- (void)sendMessageWithItem:(ChatMessageModel *)item;
@end
SocketManager.m
@interface SocketManager()
/// socket
@property (nonatomic, strong) GCDAsyncSocket *tcpSocketManager;
/// 客戶端socket集合
@property (nonatomic, strong) NSMutableArray *clientSocketArray;
/// 當(dāng)前正在傳送的item
@property (nonatomic, strong) ChatMessageModel *currentSendItem;
/// 當(dāng)前傳輸?shù)南聵酥?@property (nonatomic, assign) NSInteger currentSendTag;
/// 當(dāng)前接收到的item
@property (nonatomic, strong) ChatMessageModel *acceptItem;
/// 輸出流
@property (nonatomic, strong) NSOutputStream *outputStream;
@end
端口的監(jiān)聽
- (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;
}
// 可讀取服務(wù)端數(shù)據(jù)
[self.tcpSocketManager readDataWithTimeout:-1 tag:0];
return YES;
}
對消息內(nèi)容進行包裝發(fā)送(這篇只對文字消息處理 圖片/視頻會在下一篇進行處理)
/// 發(fā)送數(shù)據(jù)
- (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){
// 下一篇進行處理
}
}
// 創(chuàng)建消息體
- (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 代理回調(diào)
/// 新的客戶端連接上
- (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;
// 接收到非字符串類型 (預(yù)留 對圖片 / 視頻 / 音頻等的處理)
self.acceptItem.isWaitAcceptFile = self.acceptItem.chatMessageType != ChatMessageText ? YES : NO;
}
if (self.acceptItem.isWaitAcceptFile) {
// 此處對音視頻文件進行處理
}else{
self.acceptItem.finishAccept = YES;
}
// 回調(diào)出去
if ([self.delegate respondsToSelector:@selector(socketManager:itemAcceptingrefresh:)]) {
[self.delegate socketManager:self itemAcceptingrefresh:self.acceptItem];
}
[sock readDataWithTimeout:- 1 tag:0];
}
// 文件傳輸完畢后的回調(diào)
- (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];
}
// 分段傳輸完成后的 回調(diào)
- (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];
}
}
二.文字消息的相互發(fā)送
- 鍵盤工具類的發(fā)送消息的回調(diào)
- 發(fā)送完成后SockeManager的代理回調(diào)
- 接受到消息時SockeManager的代理回調(diào)
點擊鍵盤發(fā)送按鈕的回調(diào)處理
#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];
}
發(fā)送/接收完成后SockeManager的代理回調(diào)
- (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 方法后調(diào)用 需在主隊列中進行計算高度
- (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];
}
});
}