AsyncTCP 1.0.0

AsyncTCP 1.0.0

Mateusz Stompor 维护。



AsyncTCP 1.0.0

  • 作者:
  • Mateusz Stompór

AsyncTCP

Cocoapod Coverage License Build status

关于

一个小型库,简化了TCP连接的处理。为用户提供了连接到远程服务器(作为客户端)的一组类,并能够在自己的基础上托管服务器。

非阻塞和异步的,使用代理来通知关于传入数据包、连接状态更改等。您可以选择您想接收通知的轮询队列。

所有组件都松散耦合,因此代码是可测试的和经过测试的。

示例

设置一个服务器

首先定义服务器的启动参数

ServerConfiguration * configuration = [[ServerConfiguration alloc] initWithPort:57880
                                                        maximalConnectionsCount:5
                                                                      chunkSize:40
                                                              connectionTimeout:4
                                                     eventLoopMicrosecondsDelay:40
                                                  errorsBeforeConnectionClosing:3];

// Port - A number in range from 0 to 65535
// Chunk size - Buffer size
// Connection Timeout - Time of inactivity after which client's connection is going to be closed
// Maximal connections count - Number of clients allowed to connect
// Eventloop microseconds delay - Interval between server's main loop evaluations. Adjust depending on your network speed and device's resources utilization
// Errors begore connection closing - Number of errors after which the connection will be closed

使用此特定配置创建一个服务器。默认情况下,所有通知都将传递到主轮询队列。

NSObject<ServerHandle> * asyncServer = [[Server alloc] initWithConfiguratoin:configuration];

如果您希望使用不同的队列,则可以按以下方式创建实例

server = [[Server alloc] initWithConfiguratoin:configuration 
                             notificationQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)];

如果设置服务器的代理,则只发送通知。否则,将不接受连接或接收数据。要接收通知,请实现ServerDelegate协议。

ServerDelegate

接口

@interface ServerHandler: NSObject<ServerDelegate>
@end

实现

@implementation ServerHandler
-(void)newClientHasConnected: (Connection*) connection {
    // Handle the connection here somehow, set connection's delegate
}
-(void)clientHasDisconnected: (Connection*) connection {
    // Ivoked when a client disconnected or the connection hung 
}
@end

ClientDelegate

如果您想使用以下客户端分析接口

@interface ClientHandler: NSObject<ClientDelegate>
@end

实现

@implementation ClientHandler
-(void)connectionHasBeenEstablished: (Connection *) connection {
    // Handle the connection here somehow, set connection's delegate
}
-(void)connectionHasBeenClosed: (Connection*) connection {
    // Ivoked when a client disconnected or the connection hung 
}
@end

需要额外执行的一个步骤是实现 ConnectionDelegate 协议。这是一个接口,允许您在接收数据时接收通知。一旦在 ServerDelegate 的情况下接收到 newClientHasConnected 回调,或在 ClientDelegate 的情况下接收到 connectionHasBeenEstablished,立即设置一个实例为 ConnectionDelegate

ConnectionDelegate

接口

@interface ConnectionHandler: NSObject<ConnectionDelegate>
@end

实现

@implementation ConnectionHandler
-(void)connection:(NSObject<ConnectionHandle> *)connection chunkHasArrived:(NSData *)data {
    // Parse the data or pass it through 
}
@end