iOS一個簡單聊天工具的實現

Top


簡易的聊天工具


1.1 問題

Socket的英文原義是孔或者插座的意思,通常也稱作套接字,用於描述IP地址和端口,是一個通信鏈的句柄,本案例使用第三方Socket編程框架AsyncSocket框架實現一個簡易的聊天工具,並且能夠進行文件傳輸,由於沒有服務器本案例將服務器端和客戶端寫在一個程序中,如圖-1所示:

圖-1

1.2 方案

首先創建一個SingleViewApplication應用,導入AsyncSocket框架。在Storyboard中搭建聊天界面,上方的Textfield控件用於輸入接受端IP地址,中間TextView控件用於展示聊天記錄,下方的TextView用於接受用戶輸入的聊天內容,右下角有一個發送按鈕。將這三個控件分別關聯成ViewController的輸出口屬性IPTF、chatRecordTV、chatTV。

接下來首先實現聊天功能,在ViewController中定義三個屬性severSocket、clientSocket以及myNewSocket。在viewDidLoad方法中創建服務器端severSocket,將端口號設置爲8000,委託對象設置爲self。將發送按鈕關聯成viewController的動作方法send:,實現send:方法,創建客戶端對象,獲取聊天輸入框的內容轉化成NSData類型的數據發送出去。

然後ViewController遵守AsyncSocketDelegate協議,分別實現關於socket連接,數據傳輸以及數據讀取的協議方法,更新顯示聊天記錄內容。

最後實現傳輸文件功能,傳輸文件時爲了確定所傳輸文件的類型需要拼接一個消息頭,將傳輸文件的類型、名稱和大小保存到消息頭裏,通常傳輸數據的開始的100個字節是消息頭。在sender:方法中增加拼接消息頭的代碼。

接受端在接收到文件數據時首先對消息頭進行解析,獲取到接收文件的類型、大小以及名稱,然後再持續接受文件數據,接受完成後將文件保存到本地路徑。

1.3 步驟

實現此案例需要按照如下步驟進行。

步驟一:搭建聊天界面

首先創建一個SingleViewApplication應用,導入AsyncSocket框架。在Storyboard中搭建聊天界面,上方的Textfield控件用於輸入接受端IP地址,中間TextView控件用於展示聊天記錄,下方的TextView用於接受用戶輸入的聊天內容,如圖-2所示:

圖-2

然後將這三個控件分別關聯成ViewController的輸出口屬性IPTF、chatRecordTV、chatTV,代碼如下所示:

  1. @interface ViewController ()
  2. @property (weak, nonatomic) IBOutlet UITextField *IPTF;
  3. @property (weak, nonatomic) IBOutlet UITextView *chatRecordTV;
  4. @property (weak, nonatomic) IBOutlet UITextView *chatTV;
  5. @end

步驟二:實現聊天功能

首先在ViewController中定義三個屬性severSocket、clientSocket以及myNewSocket,代碼如下所示:

  1. @interface ViewController ()
  2. @property (nonatomic, strong)AsyncSocket *serverSocket;
  3. @property (nonatomic, strong)AsyncSocket *clientSocket;
  4. @property (nonatomic, strong)AsyncSocket *myNewSocket;
  5. @end

其次在viewDidLoad方法中創建服務器端severSocket,將端口號設置爲8000,委託對象設置爲self,代碼如下所示:

  1. - (void)viewDidLoad {
  2. [super viewDidLoad];
  3. self.serverSocket = [[AsyncSocket alloc]initWithDelegate:self];
  4. [self.serverSocket acceptOnPort:8000 error:nil];
  5. }

將發送按鈕關聯成viewController的動作方法send:,實現send:方法,創建客戶端對象,獲取聊天輸入框的內容轉化成NSData類型的數據發送出去,代碼如下所示:

  1. - (IBAction)send:(UIButton *)sender {
  2. [self.chatTV resignFirstResponder];
  3. //創建Socket客戶端
  4. self.clientSocket = [[AsyncSocket alloc]initWithDelegate:self];
  5. [self.clientSocket connectToHost:self.IPTF.text onPort:8000 withTimeout:-1 error:nil];
  6. //將聊天輸入框的內容轉化爲NSData
  7. NSData *data = [self.chatTV.text dataUsingEncoding:NSUTF8StringEncoding];
  8. //發送數據
  9. [self.clientSocket writeData:data withTimeout:-1 tag:0];
  10. self.chatRecordTV.text = [NSString stringWithFormat:@"%@\n我說:%@",self.chatRecordTV.text,self.chatTV.text];
  11. }

運行程序發現,點擊聊天輸入框彈出的鍵盤會擋住聊天輸入框,因此需要在接受用戶輸入的時候屏幕界面上移,viewController遵守UITextFieldDelegate和UITextViewDelegate協議,當進入輸入狀況的時候屏幕界面上移,代碼如下所示:

  1. -(BOOL)textViewShouldBeginEditing:(UITextView *)textView {
  2. [UIView beginAnimations:nil context:nil];
  3. [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
  4. [UIView setAnimationDuration:0.2];
  5. self.view.center = CGPointMake(160, self.view.center.y-200);
  6. [UIView commitAnimations];
  7. return YES;
  8. }

添加一個單擊手勢。當單擊屏幕或者點擊發送按鈕時鍵盤收回,屏幕界面恢復正常位置,代碼如下所示:

  1. //點擊發送按鈕是
  2. - (IBAction)send:(UIButton *)sender {
  3. [self.chatTV resignFirstResponder];
  4. [UIView beginAnimations:nil context:nil];
  5. [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
  6. [UIView setAnimationDuration:0.2];
  7. self.view.center = CGPointMake(160, point.y);
  8. [UIView commitAnimations];
  9. //創建Socket客戶端
  10. self.clientSocket = [[AsyncSocket alloc]initWithDelegate:self];
  11. [self.clientSocket connectToHost:self.IPTF.text onPort:8000 withTimeout:-1 error:nil];
  12. //將聊天輸入框的內容轉化爲NSData
  13. NSData *data = [self.chatTV.text dataUsingEncoding:NSUTF8StringEncoding];
  14. //發送數據
  15. [self.clientSocket writeData:data withTimeout:-1 tag:0];
  16. self.chatRecordTV.text = [NSString stringWithFormat:@"%@\n我說:%@",self.chatRecordTV.text,self.chatTV.text];
  17. }
  18. //單擊屏幕時
  19. - (IBAction)resign:(UITapGestureRecognizer *)sender {
  20. if (self.view.center.y!=point.y) {
  21. [self.chatTV resignFirstResponder];
  22. [UIView beginAnimations:nil context:nil];
  23. [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
  24. [UIView setAnimationDuration:0.2];
  25. self.view.center = point;
  26. [UIView commitAnimations];
  27. }
  28. }

最後ViewController遵守AsyncSocketDelegate協議,分別實現關於socket連接,數據傳輸以及數據讀取的協議方法,代碼如下所示:

  1. //當Socket接受一個連接的時候被調用
  2. -(void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket{
  3. //將新接受的socket持有
  4. self.myNewSocket = newSocket;
  5. }
  6. //當Socket連接並準備讀和寫調用
  7. -(void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port {
  8. //持續讀取數據
  9. [self.myNewSocket readDataWithTimeout:-1 tag:0];
  10. }
  11. //當Socket讀取數據時調用
  12. -(void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
  13.         NSString *chatStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
  14. self.chatRecordTV.text = [NSString stringWithFormat:@"%@\n對方說:%@",self.chatRecordTV.text,chatStr];
  15. [self.myNewSocket readDataWithTimeout:-1 tag:0];
  16. }
  17. //持續發送數據
  18. -(void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag {
  19. NSLog(@"發送成功");
  20. [self.myNewSocket readDataWithTimeout:-1 tag:0];
  21. }

運行程序,聊天效果如圖-3所示:

圖-3

步驟三:實現文件傳輸功能

首先定義三個屬性用於記錄傳輸文件的數據、名稱和大小,代碼如下所示:

  1. @property (strong,nonatomic) NSMutableData *allData;
  2. @property (nonatomic, copy)NSString *reciveFileName;
  3. @property (nonatomic, assign)int reciveFileLength;

文件傳輸需要拼接頭文件,將傳輸文件的類型、大小和名稱放進消息頭裏面,因此在sender:方法中增加拼接消息頭的代碼,本案例以路徑開頭區分是發送文件還是聊天,代碼如下所示:

  1. - (IBAction)send:(UIButton *)sender {
  2. [self.chatTV resignFirstResponder];
  3. [UIView beginAnimations:nil context:nil];
  4. [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
  5. [UIView setAnimationDuration:0.2];
  6. self.view.center = CGPointMake(160, point.y);
  7. [UIView commitAnimations];
  8. self.clientSocket = [[AsyncSocket alloc]initWithDelegate:self];
  9. [self.clientSocket connectToHost:self.IPTF.text onPort:8000 withTimeout:-1 error:nil];
  10. if (![self.chatTV.text hasPrefix:@"/Users"]) {
  11. NSData *data = [self.chatTV.text dataUsingEncoding:NSUTF8StringEncoding];
  12. [self.clientSocket writeData:data withTimeout:-1 tag:0];
  13. self.chatRecordTV.text = [NSString stringWithFormat:@"%@\n我說:%@",self.chatRecordTV.text,self.chatTV.text];
  14. }else {
  15. NSString *filePath = self.chatTV.text;
  16. NSData *fileData = [NSData dataWithContentsOfFile:filePath];
  17. //把頭信息添加到文件Data的前面
  18. NSString *header = [NSString stringWithFormat:@"file&&%@&&%d",[filePath lastPathComponent],fileData.length];
  19. //把頭字符串轉成data
  20. NSData *headerData = [header dataUsingEncoding:NSUTF8StringEncoding];
  21. //把頭替換進100個字節的data裏面
  22. NSMutableData *sendAllData = [NSMutableData dataWithLength:100];
  23. [sendAllData replaceBytesInRange:NSMakeRange(0, headerData.length) withBytes:headerData.bytes];
  24. [sendAllData appendData:fileData];
  25. NSLog(@"%@",header);
  26. NSLog(@"SendLength = %d",sendAllData.length);
  27. [self.clientSocket writeData:sendAllData withTimeout:-1 tag:0];
  28. self.chatRecordTV.text = [NSString stringWithFormat:@"%@\n我說:%@正在發送",self.chatRecordTV.text,self.chatTV.text];
  29. }
  30. }

在讀取數據的方法中首先獲取消息頭信息,如果傳遞過來的是文件則獲取到傳輸文件的類型、大小和名稱,持續讀取文件數據,將文件保存到本地路徑,接受完成更新聊天記錄,代碼如下所示:

  1. -(void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
  2. if (data.length>=100) {
  3. NSData *headerData = [data subdataWithRange:NSMakeRange(0, 100)];
  4. NSString *headerStr = [[NSString alloc]initWithData:headerData encoding:NSUTF8StringEncoding];
  5. if (headerStr&& [headerStr componentsSeparatedByString:@"&&"].count==3) {
  6. isFile = YES;
  7. }
  8. }
  9. if (isFile == NO) {
  10. NSString *chatStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
  11. self.chatRecordTV.text = [NSString stringWithFormat:@"%@\n對方說:%@",self.chatRecordTV.text,chatStr];
  12. }
  13. if (isFile==YES) {
  14. if (data.length>=100) {
  15. NSData *headerData = [data subdataWithRange:NSMakeRange(0, 100)];
  16. NSString *headerStr = [[NSString alloc]initWithData:headerData encoding:NSUTF8StringEncoding];
  17. if (headerStr&& [headerStr componentsSeparatedByString:@"&&"].count==3) {
  18. NSArray *headers = [headerStr componentsSeparatedByString:@"&&"];
  19. NSString *type = [headers objectAtIndex:0];
  20. if ([type isEqualToString:@"file"]) {
  21. self.reciveFileName = [headers objectAtIndex:1];
  22. self.reciveFileLength = [[headers objectAtIndex:2] intValue];
  23. NSData *subFileData = [data subdataWithRange:NSMakeRange(100, data.length-100)];
  24. if (!self.allData) {
  25. self.allData = [NSMutableData data];
  26. }
  27. [self.allData appendData:subFileData];
  28. }
  29. }else {//沒有消息頭的情況下
  30. [self.allData appendData:data];
  31. }
  32. }else {//沒有消息頭的情況下
  33. [self.allData appendData:data];
  34. }
  35. NSLog(@"%d,%d",self.allData.length,self.reciveFileLength);
  36. if (self.allData.length == self.reciveFileLength ) {
  37. NSLog(@"接受完成");
  38. NSString *filePath = [@"/Users/Vivian/Documents" stringByAppendingPathComponent:self.reciveFileName];
  39. [self.allData writeToFile:filePath atomically:YES];
  40. self.chatRecordTV.text = [NSString stringWithFormat:@"%@\n對方說:成功接收文件%@",self.chatRecordTV.text,self.reciveFileName];
  41. self.allData = nil;
  42. isFile = NO;
  43. }
  44. if (isFile == YES) {
  45. //如果有數據能夠持續接受
  46. [self.myNewSocket readDataWithTimeout:-1 tag:0];
  47. }
  48. }
  49. }

運行程序,傳輸文件效果如圖-4所示:

圖-4

1.4 完整代碼

本案例中,ViewController.m文件中的完整代碼如下所示:

  1. #import "ViewController.h"
  2. @interface ViewController () <AsyncSocketDelegate,UITextFieldDelegate,UITextViewDelegate> {
  3. BOOL isFile;
  4. CGPoint point;
  5. }
  6. @property (weak, nonatomic) IBOutlet UITextField *IPTF;
  7. @property (weak, nonatomic) IBOutlet UITextView *chatRecordTV;
  8. @property (weak, nonatomic) IBOutlet UITextView *chatTV;
  9. @property (nonatomic, strong)AsyncSocket *serverSocket;
  10. @property (nonatomic, strong)AsyncSocket *clientSocket;
  11. @property (nonatomic, strong)AsyncSocket *myNewSocket;
  12. @property (strong,nonatomic) NSMutableData *allData;
  13. @property (nonatomic, copy)NSString *reciveFileName;
  14. @property (nonatomic, assign)int reciveFileLength;
  15. @end
  16. @implementation ViewController
  17. - (void)viewDidLoad {
  18. [super viewDidLoad];
  19. self.serverSocket = [[AsyncSocket alloc]initWithDelegate:self];
  20. [self.serverSocket acceptOnPort:8000 error:nil];
  21. point = self.view.center;
  22. self.allData = [NSMutableData data];
  23. isFile = NO;
  24. }
  25. -(void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket{
  26. //將新接受的socket持有
  27. self.myNewSocket = newSocket;
  28. }
  29. -(void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port {
  30. [self.myNewSocket readDataWithTimeout:-1 tag:0];
  31. }
  32. -(void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
  33. if (data.length>=100) {
  34. NSData *headerData = [data subdataWithRange:NSMakeRange(0, 100)];
  35. NSString *headerStr = [[NSString alloc]initWithData:headerData encoding:NSUTF8StringEncoding];
  36. if (headerStr&& [headerStr componentsSeparatedByString:@"&&"].count==3) {
  37. isFile = YES;
  38. }
  39. }
  40. if (isFile == NO) {
  41. NSString *chatStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
  42. self.chatRecordTV.text = [NSString stringWithFormat:@"%@\n對方說:%@",self.chatRecordTV.text,chatStr];
  43. }
  44. if (isFile==YES) {
  45. if (data.length>=100) {
  46. NSData *headerData = [data subdataWithRange:NSMakeRange(0, 100)];
  47. NSString *headerStr = [[NSString alloc]initWithData:headerData encoding:NSUTF8StringEncoding];
  48. if (headerStr&& [headerStr componentsSeparatedByString:@"&&"].count==3) {
  49. NSArray *headers = [headerStr componentsSeparatedByString:@"&&"];
  50. NSString *type = [headers objectAtIndex:0];
  51. if ([type isEqualToString:@"file"]) {
  52. self.reciveFileName = [headers objectAtIndex:1];
  53. self.reciveFileLength = [[headers objectAtIndex:2] intValue];
  54. NSData *subFileData = [data subdataWithRange:NSMakeRange(100, data.length-100)];
  55. if (!self.allData) {
  56. self.allData = [NSMutableData data];
  57. }
  58. [self.allData appendData:subFileData];
  59. }
  60. }else {//沒有消息頭的情況下
  61. [self.allData appendData:data];
  62. }
  63. }else {//沒有消息頭的情況下
  64. [self.allData appendData:data];
  65. }
  66. NSLog(@"%d,%d",self.allData.length,self.reciveFileLength);
  67. if (self.allData.length == self.reciveFileLength ) {
  68. NSLog(@"接受完成");
  69. NSString *filePath = [@"/Users/Vivian/Documents" stringByAppendingPathComponent:self.reciveFileName];
  70. [self.allData writeToFile:filePath atomically:YES];
  71. self.chatRecordTV.text = [NSString stringWithFormat:@"%@\n對方說:成功接收文件%@",self.chatRecordTV.text,self.reciveFileName];
  72. self.allData = nil;
  73. isFile = NO;
  74. }
  75. if (isFile == YES) {
  76. //如果有數據能夠持續接受
  77. [self.myNewSocket readDataWithTimeout:-1 tag:0];
  78. }
  79. }
  80. }
  81. -(void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag {
  82. NSLog(@"發送成功");
  83. [self.myNewSocket readDataWithTimeout:-1 tag:0];
  84. }
  85. -(BOOL)textViewShouldBeginEditing:(UITextView *)textView {
  86. [UIView beginAnimations:nil context:nil];
  87. [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
  88. [UIView setAnimationDuration:0.2];
  89. self.view.center = CGPointMake(160, self.view.center.y-200);
  90. [UIView commitAnimations];
  91. return YES;
  92. }
  93. - (IBAction)send:(UIButton *)sender {
  94. [self.chatTV resignFirstResponder];
  95. [UIView beginAnimations:nil context:nil];
  96. [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
  97. [UIView setAnimationDuration:0.2];
  98. self.view.center = CGPointMake(160, point.y);
  99. [UIView commitAnimations];
  100. self.clientSocket = [[AsyncSocket alloc]initWithDelegate:self];
  101. [self.clientSocket connectToHost:self.IPTF.text onPort:8000 withTimeout:-1 error:nil];
  102. if (![self.chatTV.text hasPrefix:@"/Users"]) {
  103. NSData *data = [self.chatTV.text dataUsingEncoding:NSUTF8StringEncoding];
  104. [self.clientSocket writeData:data withTimeout:-1 tag:0];
  105. self.chatRecordTV.text = [NSString stringWithFormat:@"%@\n我說:%@",self.chatRecordTV.text,self.chatTV.text];
  106. }else {
  107. NSString *filePath = self.chatTV.text;
  108. NSData *fileData = [NSData dataWithContentsOfFile:filePath];
  109. //把頭信息添加到文件Data的前面
  110. NSString *header = [NSString stringWithFormat:@"file&&%@&&%d",[filePath lastPathComponent],fileData.length];
  111. //把頭字符串轉成data
  112. NSData *headerData = [header dataUsingEncoding:NSUTF8StringEncoding];
  113. //把頭替換進100個字節的data裏面
  114. NSMutableData *sendAllData = [NSMutableData dataWithLength:100];
  115. [sendAllData replaceBytesInRange:NSMakeRange(0, headerData.length) withBytes:headerData.bytes];
  116. [sendAllData appendData:fileData];
  117. NSLog(@"%@",header);
  118. NSLog(@"SendLength = %d",sendAllData.length);
  119. [self.clientSocket writeData:sendAllData withTimeout:-1 tag:0];
  120. self.chatRecordTV.text = [NSString stringWithFormat:@"%@\n我說:%@正在發送",self.chatRecordTV.text,self.chatTV.text];
  121. }
  122. }
  123. - (IBAction)done:(UITextField *)sender {
  124. [self.IPTF resignFirstResponder];
  125. }
  126. - (IBAction)resign:(UITapGestureRecognizer *)sender {
  127. if (self.view.center.y!=point.y) {
  128. [self.chatTV resignFirstResponder];
  129. [UIView beginAnimations:nil context:nil];
  130. [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
  131. [UIView setAnimationDuration:0.2];
  132. self.view.center = point;
  133. [UIView commitAnimations];
  134. }
  135. }
  136. @end

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章