// // XUDPServer.m // xcmd // // Created by mac on 2025/2/17. // #import #import "XUDPServer.h" #import "UDPHandler.h" #define PORT 6001 @interface XUDPServer() { @private GCDAsyncUdpSocket *serverSocket; } @end @implementation XUDPServer +(instancetype)sharedInstance { static XUDPServer* _sharedInstance = nil; static dispatch_once_t oncePredicate; dispatch_once (&oncePredicate, ^{ _sharedInstance = [[XUDPServer alloc] init]; }); return _sharedInstance; } -(instancetype)init { if (self = [super init]) { return self; } return nil; } - (void) start { NSLog(@"XS- start udp server"); dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); serverSocket=[[GCDAsyncUdpSocket alloc]initWithDelegate:self delegateQueue:queue]; NSError *error = nil; if (![serverSocket bindToPort:PORT error:&error]) { NSLog(@"Error starting server (bind): %@", error); return; } if (![serverSocket beginReceiving:&error]) { [serverSocket close]; NSLog(@"Error starting server (recv): %@", error); return; } } // 网络连接成功后 自动回调 - (void)udpSocket:(GCDAsyncUdpSocket *)sock didConnectToAddress:(NSData *)address { NSLog(@"已连接到用户:ip:%@",[[NSString alloc]initWithData:address encoding:NSUTF8StringEncoding]); } -(void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext { @autoreleasepool { NSString *datastr=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; // 将数据回写给发送数据的用户 NSLog(@"XS- UDP Request>>>> %@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); UDPHandler *handle = [UDPHandler sharedInstance]; NSString *res = [handle handle:datastr]; NSLog(@"UDP Response:%@" , res); [sock sendData:[res dataUsingEncoding:NSUTF8StringEncoding] toAddress:address withTimeout:-1 tag:300]; /* [sock sendData:[[NSString stringWithFormat:@"服务器收到客户端消息返回%@",datastr] dataUsingEncoding:NSUTF8StringEncoding] toAddress:address withTimeout:-1 tag:300]; */ } } - (void)udpSocket:(GCDAsyncUdpSocket *)sock didNotConnect:(NSError * _Nullable)error { NSLog(@"didNotConnect:%@", error); } - (void)udpSocket:(GCDAsyncUdpSocket *)sock didSendDataWithTag:(long)tag { NSLog(@"didSendDataWithTag:%ld", tag); } - (void)udpSocket:(GCDAsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError * _Nullable)error { NSLog(@"didNotSendDataWithTag:%@", error); } - (void)udpSocketDidClose:(GCDAsyncUdpSocket *)sock withError:(NSError * _Nullable)error { NSLog(@"withError:%@", error); } @end