1、將GCDAsyncSocket框架導入項目中
2、代碼如下:
#import "ViewController.h"
#import "ServertListener.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//1、創建服務監聽器
ServertListener *listener = [[ServertListener alloc] init];
//2、開始監聽
[listener start];
//開啓主運行循環
[[NSRunLoop mainRunLoop]run];
}
@end
#import <Foundation/Foundation.h>
@interface ServertListener : NSObject
/**開始監聽*/
-(void)start;
@end
#import "ServertListener.h"
#import "GCDAsyncSocket.h"
@interface ServertListener()<GCDAsyncSocketDelegate>
/**
* 服務端Socket
*/
@property (nonatomic, strong) GCDAsyncSocket *serverSocket;
/**
* 所有的客戶端
*/
@property (nonatomic, strong) NSMutableArray *clientSockets;
@property (nonatomic, strong) NSMutableString *log;//日誌
@end
@implementation ServertListener
-(NSMutableString *)log{
if (!_log) {
_log = [NSMutableString string];
}
return _log;
}
-(NSMutableArray *)clientSockets{
if (!_clientSockets) {
_clientSockets = [NSMutableArray array];
}
return _clientSockets;
}
-(instancetype)init{
if (self = [super init]) {
self.serverSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_global_queue(0, 0)];
}
return self;
}
-(void)start{
NSError *error = nil;
BOOL success = [self.serverSocket acceptOnPort:5239 error:&error];
if (success) {
NSLog(@"5239端口開啓成功,監聽客戶端請求連接...");
}else{
NSLog(@"5239端口開啓失敗");
NSLog(@"%@",error);
}
}
#pragma mark--代理
-(void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket{
NSLog(@"%@ IP : %@: %zd 客戶端請求連接",newSocket,newSocket.connectedHost,newSocket.connectedPort);
//1、將客戶端socket保存下來
[self.clientSockets addObject:newSocket];
//2、一旦同意連接 ,監聽數據讀取,如果有數據會掉用下面的代理方法
[newSocket readDataWithTimeout:-1 tag:0];
}
#pragma mark-私有方法-寫數據
-(void)writeDataWithSocket:(GCDAsyncSocket *)clientSocket str:(NSString *)str{
[clientSocket writeData:[str dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
}
-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
//1、客戶端傳遞數據轉換成字符串
NSString *clientStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
self.log = [NSMutableString stringWithFormat:@"%@",clientStr];
for (GCDAsyncSocket *socket in self.clientSockets) {
if (![sock isEqual:socket]) {
[self writeDataWithSocket:socket str:self.log];
}
}
//2、監聽數據讀取
[sock readDataWithTimeout:-1 tag:0];
}
-(void)exitWithSocket:(GCDAsyncSocket *)clientSocket{
[self writeDataWithSocket:clientSocket str:@"退出成功\n"];
[self.clientSockets removeObject:clientSocket];
}
-(void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag{
NSLog(@"數據發送成功...");
}
@end
3、端口開啓,監聽客戶端連接
4、模擬客戶端連接
5、服務端監聽到客戶端的連接
6、客戶端發送信息
7、服務端監聽到信息的發送