本文並非講述如何用原始的socket進行通訊,而是用第三方類庫AsyncSocket。它對socket進行了封裝,使得TCP通訊簡單了許多,方便咱們開發,我的認爲若要認真學習TCP/IP,最好別用第三方庫。本文簡述如何用這個第三方庫來進行多人聊天
網絡
進行網絡開發,系統庫是少不了的,導入CFNetWork.framework。socket
將AsyncSocket庫添加到咱們的項目裏面佈局
再添加頭文件學習
#import "AsyncSocket.h"添加代理協議 AsyncSocketDelegate
在 ViewController.h 聲明成員變量和事件spa
IBOutlet UITextField* _ipFiled;//IP IBOutlet UITextField* _textFiled;//send message IBOutlet UITextView* _textView;//receive message //客戶端 AsyncSocket* _sendSocket; //服務端 AsyncSocket* _recvSocket; NSMutableArray* _socketArray;
//鏈接 - (IBAction)conToHost:(id)sender; //發送 - (IBAction)sendText:(id)sender;
這裏別忘了要將控件和對象進行綁定。.net
其他代碼以下:3d
- (void)viewDidLoad { [super viewDidLoad]; _socketArray = [[NSMutableArray alloc] init]; //服務端 _recvSocket = [[AsyncSocket alloc] initWithDelegate:self]; //監聽客戶端來鏈接 [_recvSocket acceptOnPort:5678 error:nil]; //客戶端 _sendSocket = [[AsyncSocket alloc] initWithDelegate:self]; } //監聽到客戶端鏈接 - (void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket{ [_socketArray addObject:newSocket]; //等待客戶端發送消息 [newSocket readDataWithTimeout:-1 tag:0]; } //監聽到客戶端發送消息 - (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{ //處理客戶端發來的消息 data NSString* str = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]; /* ip:你吃飯了 ip:121.2.3.90 */ _textView.text = [NSString stringWithFormat:@"%@%@:%@\n", _textView.text, sock.connectedHost, str]; //繼續監聽客戶端發送消息 [sock readDataWithTimeout:-1 tag:0]; } //客戶端 //鏈接到服務端 - (void)conToHost:(id)sender { //若是是鏈接狀態,先斷開鏈接 if (_sendSocket.isConnected) { [_sendSocket disconnect]; } //鏈接 [_sendSocket connectToHost:_ipFiled.text onPort:5678 withTimeout:30 error:nil]; } //鏈接成功 - (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port { NSLog(@"鏈接成功"); }
完整Demo在這裏。若是沒有積分請留郵箱。
代理