效果图:
IP:服务器端的地址
PORT: 端口,可以设置为任意一个
代码:
服务器端连接:
int port = [_txf_PORT.stringValue intValue];
if (port < 0 || port > 65535)
{
[_txf_PORT setStringValue:@""];
port = 0;
}
NSString *ip = _txf_IP.stringValue;
NSError *error = nil;
NSLog(@"%@", _txf_IP.stringValue);
NSLog(@"%d", port);
if(![listenSocket acceptOnInterface:ip port:port error:&error])
{
[self logError:FORMAT(@"Error starting server: %@", error)];
return;
}
[self logInfo:FORMAT(@"Echo server started on port %hu", [listenSocket localPort])];
服务器端的连接成功返回:
- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket
{
// This method is executed on the socketQueue (not the main thread)
@synchronized(connectedSockets)
{
[connectedSockets addObject:newSocket];
}
NSString *host = [newSocket connectedHost];
UInt16 port = [newSocket connectedPort];
dispatch_async(dispatch_get_main_queue(), ^{
@autoreleasepool {
[self logInfo:FORMAT(@"Accepted client %@:%hu", host, port)];
}
});
NSString *welcomeMsg = @"Welcome to the AsyncSocket Echo Server\r\n";
NSData *welcomeData = [welcomeMsg dataUsingEncoding:NSUTF8StringEncoding];
[newSocket writeData:welcomeData withTimeout:-1 tag:WELCOME_MSG];
[newSocket readDataToData:[GCDAsyncSocket CRLFData] withTimeout:READ_TIMEOUT tag:0];
}
服务器端获取数据:
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
// This method is executed on the socketQueue (not the main thread)
dispatch_async(dispatch_get_main_queue(), ^{
@autoreleasepool {
NSData *strData = [data subdataWithRange:NSMakeRange(0, [data length] - 2)];
NSString *msg = [[NSString alloc] initWithData:strData encoding:NSUTF8StringEncoding];
if (msg)
{
[self logMessage:msg];
}
else
{
[self logError:@"Error converting received data into UTF-8 String"];
}
}
});
// Echo message back to client
[sock writeData:data withTimeout:-1 tag:ECHO_MSG];
}
客户端连接:
socketQueue = dispatch_queue_create("socketQueue", NULL);
sendSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:socketQueue];
NSError *error;
isConnect = [sendSocket connectToHost:_txf_IP.stringValue onPort:[_txf_PORT.stringValue intValue] error: &error];
if (!isConnect)
{
NSLog(@"connect error: %@", error);
return;
}
客户端发送数据:
- (IBAction)btn_SendData:(id)sender {
NSData* data = [[NSString stringWithFormat:@"%@\r\n", _text_Content.string] dataUsingEncoding: NSUTF8StringEncoding];
if (isConnect) {
[sendSocket writeData: data withTimeout: -1 tag: 0];
}
}
源码地址:SocketDemo
基于CocoaAsyncSocket创建的简单SocketDemo例子-Swift文档类资源-CSDN文库
基于CocoaAsyncSocket:CocoaAsyncSocket (有兴趣的可以深入研究)