總結(jié)知識(shí)點(diǎn)兒,僅供參考:如有錯(cuò)誤,歡迎指正;
ios 網(wǎng)絡(luò)通信的方法有兩大類:使用socket方式進(jìn)行通信 和 使用asynsocket類庫(kù)進(jìn)行通信
建議使用的時(shí)候用asynsocket更好些 因?yàn)槭莿e人已經(jīng)封裝好的類庫(kù),比較穩(wěn)定 Socket通信的方法更靈活 因?yàn)榭刂贫际亲约涸谧龅氖虑?/p>
1,直接使用Socket的方式
以TCP為例,對(duì)于TCP來說,區(qū)分服務(wù)端和客戶端.
服務(wù)端:通常的方法是服務(wù)器啟動(dòng)后監(jiān)聽 是否有客戶端連接 如果有連接 則建立與客戶端的通信 客戶端的方法通常是連接服務(wù)端 當(dāng)連接成功后 就希望發(fā)送數(shù)據(jù).
服務(wù)端代碼:
#import"ViewController.h"
// 使用CocoPods使用<>, 可以指定路徑
#import
#import"GNASocket.h"
@interfaceViewController ()
@property(weak, nonatomic) IBOutlet UITextField *portTF;
@property(weak, nonatomic) IBOutlet UITextView *message;// 多行文本輸入框
@property(weak, nonatomic) IBOutlet UITextField *content;
@property(nonatomic, strong) GCDAsyncSocket *clientSocket;// 為客戶端生成的socket
// 服務(wù)器socket
@property(nonatomic, strong) GCDAsyncSocket *serverSocket;
@end
@implementationViewController
- (void)viewDidLoad
{
[superviewDidLoad];
}
// 服務(wù)端監(jiān)聽某個(gè)端口
- (IBAction)listen:(UIButton *)sender
{
// 1. 創(chuàng)建服務(wù)器socket
self.serverSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
// 2. 開放哪些端口
NSError *error = nil;
BOOL result = [self.serverSocket acceptOnPort:self.portTF.text.integerValue error:&error];
// 3. 判斷端口號(hào)是否開放成功
if(result) {
[self addText:@"端口開放成功"];
}else{
[self addText:@"端口開放失敗"];
}
}
// 發(fā)送
- (IBAction)sendMessage:(UIButton *)sender
{
NSData *data = [self.content.text dataUsingEncoding:NSUTF8StringEncoding];
[self.clientSocket writeData:data withTimeout:-1tag:0];
GNASocket *socket = [GNASocket defaultScocket];
[socket.mySocket readDataWithTimeout:-1tag:0];
}
// 接收消息
- (IBAction)receiveMassage:(UIButton *)sender
{
[self.clientSocket readDataWithTimeout:-1tag:0];
}
// textView填寫內(nèi)容
- (void)addText:(NSString *)text
{
self.message.text = [self.message.text stringByAppendingFormat:@"%@\n", text];
}
- (void)didReceiveMemoryWarning
{
[superdidReceiveMemoryWarning];
}
#pragma mark - GCDAsyncSocketDelegate
// 當(dāng)客戶端鏈接服務(wù)器端的socket, 為客戶端單生成一個(gè)socket
- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket
{
[self addText:@"鏈接成功"];
//IP: newSocket.connectedHost
//端口號(hào): newSocket.connectedPort
[self addText:[NSString stringWithFormat:@"鏈接地址:%@", newSocket.connectedHost]];
[self addText:[NSString stringWithFormat:@"端口號(hào):%hu", newSocket.connectedPort]];
// short: %hd
// unsigned short: %hu
// 存儲(chǔ)新的端口號(hào)
self.clientSocket = newSocket;
}
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
NSString *message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[self addText:message];
}
@end
客戶端代碼:
#import"SecondViewController.h"
#import
#import"GNASocket.h"
@interfaceSecondViewController ()
@property(weak, nonatomic) IBOutlet UITextField *addressTF;
@property(weak, nonatomic) IBOutlet UITextField *portTF;
@property(weak, nonatomic) IBOutlet UITextField *message;
@property(weak, nonatomic) IBOutlet UITextView *content;
@property(nonatomic, strong) GCDAsyncSocket *socket;
@end
@implementationSecondViewController
- (void)viewDidLoad
{
[superviewDidLoad];
}
// 和服務(wù)器進(jìn)行鏈接
- (IBAction)connect:(UIButton *)sender
{
// 1. 創(chuàng)建socket
self.socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
// 2. 與服務(wù)器的socket鏈接起來
NSError *error = nil;
BOOL result = [self.socket connectToHost:self.addressTF.text onPort:self.portTF.text.integerValue error:&error];
// 3. 判斷鏈接是否成功
if(result) {
[self addText:@"客戶端鏈接服務(wù)器成功"];
}else{
[self addText:@"客戶端鏈接服務(wù)器失敗"];
}
}
// 接收數(shù)據(jù)
- (IBAction)receiveMassage:(UIButton *)sender
{
[self.socket readDataWithTimeout:-1tag:0];
}
// 發(fā)送消息
- (IBAction)sendMassage:(UIButton *)sender
{
[self.socket writeData:[self.message.text dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1tag:0];
}
// textView填寫內(nèi)容
- (void)addText:(NSString *)text
{
self.content.text = [self.content.text stringByAppendingFormat:@"%@\n", text];
}
- (void)didReceiveMemoryWarning
{
[superdidReceiveMemoryWarning];
}
#pragma mark - GCDAsyncSocketDelegate
// 客戶端鏈接服務(wù)器端成功, 客戶端獲取地址和端口號(hào)
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
{
[self addText:[NSString stringWithFormat:@"鏈接服務(wù)器%@", host]];
GNASocket *socket = [GNASocket defaultScocket];
socket.mySocket = self.socket;
}
// 客戶端已經(jīng)獲取到內(nèi)容
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
NSString *content = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[self addText:content];
}
@end
為通信傳值寫一個(gè)單例:
#import
#import
@interfaceGNASocket : NSObject
@property(nonatomic, strong) GCDAsyncSocket *mySocket;
+ (GNASocket *)defaultScocket;
@end
//.m
#import"GNASocket.h"
@implementationGNASocket
+ (GNASocket *)defaultScocket
{
staticGNASocket *socket = nil;
staticdispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
socket = [[GNASocket alloc] init];
});
returnsocket;
}
效果圖:
@end