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、服务端监听到信息的发送