总结知识点儿,仅供参考:如有错误,欢迎指正;
ios 网络通信的方法有两大类:使用socket方式进行通信 和 使用asynsocket类库进行通信
建议使用的时候用asynsocket更好些 因为是别人已经封装好的类库,比较稳定 Socket通信的方法更灵活 因为控制都是自己在做的事情
1,直接使用Socket的方式
以TCP为例,对于TCP来说,区分服务端和客户端.
服务端:通常的方法是服务器启动后监听 是否有客户端连接 如果有连接 则建立与客户端的通信 客户端的方法通常是连接服务端 当连接成功后 就希望发送数据.
服务端代码:
#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
// 服务器socket
@property(nonatomic, strong) GCDAsyncSocket *serverSocket;
@end
@implementationViewController
- (void)viewDidLoad
{
[superviewDidLoad];
}
// 服务端监听某个端口
- (IBAction)listen:(UIButton *)sender
{
// 1. 创建服务器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. 判断端口号是否开放成功
if(result) {
[self addText:@"端口开放成功"];
}else{
[self addText:@"端口开放失败"];
}
}
// 发送
- (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填写内容
- (void)addText:(NSString *)text
{
self.message.text = [self.message.text stringByAppendingFormat:@"%@\n", text];
}
- (void)didReceiveMemoryWarning
{
[superdidReceiveMemoryWarning];
}
#pragma mark - GCDAsyncSocketDelegate
// 当客户端链接服务器端的socket, 为客户端单生成一个socket
- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket
{
[self addText:@"链接成功"];
//IP: newSocket.connectedHost
//端口号: newSocket.connectedPort
[self addText:[NSString stringWithFormat:@"链接地址:%@", newSocket.connectedHost]];
[self addText:[NSString stringWithFormat:@"端口号:%hu", newSocket.connectedPort]];
// short: %hd
// unsigned short: %hu
// 存储新的端口号
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];
}
// 和服务器进行链接
- (IBAction)connect:(UIButton *)sender
{
// 1. 创建socket
self.socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
// 2. 与服务器的socket链接起来
NSError *error = nil;
BOOL result = [self.socket connectToHost:self.addressTF.text onPort:self.portTF.text.integerValue error:&error];
// 3. 判断链接是否成功
if(result) {
[self addText:@"客户端链接服务器成功"];
}else{
[self addText:@"客户端链接服务器失败"];
}
}
// 接收数据
- (IBAction)receiveMassage:(UIButton *)sender
{
[self.socket readDataWithTimeout:-1tag:0];
}
// 发送消息
- (IBAction)sendMassage:(UIButton *)sender
{
[self.socket writeData:[self.message.text dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1tag:0];
}
// textView填写内容
- (void)addText:(NSString *)text
{
self.content.text = [self.content.text stringByAppendingFormat:@"%@\n", text];
}
- (void)didReceiveMemoryWarning
{
[superdidReceiveMemoryWarning];
}
#pragma mark - GCDAsyncSocketDelegate
// 客户端链接服务器端成功, 客户端获取地址和端口号
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
{
[self addText:[NSString stringWithFormat:@"链接服务器%@", host]];
GNASocket *socket = [GNASocket defaultScocket];
socket.mySocket = self.socket;
}
// 客户端已经获取到内容
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
NSString *content = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[self addText:content];
}
@end
为通信传值写一个单例:
#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