網絡通信,有一個CocoaAsyncSocket這個類庫,然後建兩個工程,分别寫伺服器端和用戶端的,用戶端的IP位址要寫自己電腦的,端口号要相同。
可以GCD 或者RunLoop 我用的是GCD的,直接上代碼,有注釋,都能看懂
- 伺服器.m裡的
- -
import “ViewController.h”
import “GCDAsyncSocket.h”
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *portF;
@property (weak, nonatomic) IBOutlet UITextField *messageTF;
@property (weak, nonatomic) IBOutlet UITextView *showContentMessageTV;
//伺服器socket(開放端口,監聽用戶端socket的連結)
@property (nonatomic) GCDAsyncSocket *serverSocket;
//保護用戶端socket
@property (nonatomic) GCDAsyncSocket *clientSocket;
@end
@implementation ViewController
pragma mark - 伺服器socket Delegate
-
(void)socket:(GCDAsyncSocket )sock didAcceptNewSocket:(GCDAsyncSocket )newSocket{
//儲存用戶端的socket
self.clientSocket = newSocket;
[self showMessageWithStr:@”連結成功”];
[self showMessageWithStr:[NSString stringWithFormat:@”伺服器位址:%@ -端口: %d”, newSocket.connectedHost, newSocket.connectedPort]];
[self.clientSocket readDataWithTimeout:-1 tag:0];
}
//收到消息
- (void)socket:(GCDAsyncSocket )sock didReadData:(NSData )data withTag:(long)tag{
NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[self showMessageWithStr:text];
[self.clientSocket readDataWithTimeout:-1 tag:0];
}
//發送消息
- (IBAction)sendMessage:(id)sender {
NSDictionary *dic = [[NSDictionary alloc]init];
[dic setValue:@”id” forKey:@”12121”];
// NSData *data = [self.messageTF.text dataUsingEncoding:NSUTF8StringEncoding];
NSData *data = [[self dictionaryToJson:dic] dataUsingEncoding:NSUTF8StringEncoding];
//withTimeout -1:無窮大,一直等
//tag:消息标記
[self.clientSocket writeData:data withTimeout:-1 tag:0];
}
-(NSString*)dictionaryToJson:(NSDictionary *)dic
{
NSError *parseError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
//開始監聽
- (IBAction)startReceive:(id)sender {
//2、開放哪一個端口
NSError *error = nil;
BOOL result = [self.serverSocket acceptOnPort:self.portF.text.integerValue error:&error];
if (result && error == nil) {
//開放成功
[self showMessageWithStr:@”開放成功”];
}
}
//接受消息,socket是用戶端socket,表示從哪一個用戶端讀取消息
- (IBAction)ReceiveMessage:(id)sender {
[self.clientSocket readDataWithTimeout:11 tag:0];
}
-
(void)showMessageWithStr:(NSString *)str{
self.showContentMessageTV.text = [self.showContentMessageTV.text stringByAppendingFormat:@”%@\n”,str];
}
-
(void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// 1、初始化伺服器socket,在主線程力回調
self.serverSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
}
-
(void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
- 用戶端.m裡的
- -
import “ViewController.h”
import “GCDAsyncSocket.h”
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *portF;
@property (weak, nonatomic) IBOutlet UITextField *messageTF;
@property (weak, nonatomic) IBOutlet UITextView *showContentMessageTV;
//伺服器socket(開放端口,監聽用戶端socket的連結)
@property (nonatomic) GCDAsyncSocket *serverSocket;
//保護用戶端socket
@property (nonatomic) GCDAsyncSocket *clientSocket;
@end
@implementation ViewController
pragma mark - 伺服器socket Delegate
-
(void)socket:(GCDAsyncSocket )sock didAcceptNewSocket:(GCDAsyncSocket )newSocket{
//儲存用戶端的socket
self.clientSocket = newSocket;
[self showMessageWithStr:@”連結成功”];
[self showMessageWithStr:[NSString stringWithFormat:@”伺服器位址:%@ -端口: %d”, newSocket.connectedHost, newSocket.connectedPort]];
[self.clientSocket readDataWithTimeout:-1 tag:0];
}
//收到消息
- (void)socket:(GCDAsyncSocket )sock didReadData:(NSData )data withTag:(long)tag{
NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[self showMessageWithStr:text];
[self.clientSocket readDataWithTimeout:-1 tag:0];
}
//發送消息
- (IBAction)sendMessage:(id)sender {
NSDictionary *dic = [[NSDictionary alloc]init];
[dic setValue:@”id” forKey:@”12121”];
// NSData *data = [self.messageTF.text dataUsingEncoding:NSUTF8StringEncoding];
NSData *data = [[self dictionaryToJson:dic] dataUsingEncoding:NSUTF8StringEncoding];
//withTimeout -1:無窮大,一直等
//tag:消息标記
[self.clientSocket writeData:data withTimeout:-1 tag:0];
}
-(NSString*)dictionaryToJson:(NSDictionary *)dic
{
NSError *parseError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
//開始監聽
- (IBAction)startReceive:(id)sender {
//2、開放哪一個端口
NSError *error = nil;
BOOL result = [self.serverSocket acceptOnPort:self.portF.text.integerValue error:&error];
if (result && error == nil) {
//開放成功
[self showMessageWithStr:@”開放成功”];
}
}
//接受消息,socket是用戶端socket,表示從哪一個用戶端讀取消息
- (IBAction)ReceiveMessage:(id)sender {
[self.clientSocket readDataWithTimeout:11 tag:0];
}
-
(void)showMessageWithStr:(NSString *)str{
self.showContentMessageTV.text = [self.showContentMessageTV.text stringByAppendingFormat:@”%@\n”,str];
}
-
(void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// 1、初始化伺服器socket,在主線程力回調
self.serverSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
}
-
(void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end