FBTCPSocket.m 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /**
  2. * Copyright (c) 2015-present, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the BSD-style license found in the
  6. * LICENSE file in the root directory of this source tree. An additional grant
  7. * of patent rights can be found in the PATENTS file in the same directory.
  8. */
  9. #import "FBTCPSocket.h"
  10. @interface FBTCPSocket()
  11. @property (readonly, nonatomic) dispatch_queue_t socketQueue;
  12. @property (readonly, nonatomic) GCDAsyncSocket *listeningSocket;
  13. @property (readonly, nonatomic) NSMutableArray *connectedClients;
  14. @property (readonly, nonatomic) uint16_t port;
  15. @end
  16. @interface FBTCPSocket(AsyncSocket) <GCDAsyncSocketDelegate>
  17. @end
  18. @implementation FBTCPSocket
  19. - (instancetype)initWithPort:(uint16_t)port
  20. {
  21. if ((self = [super init])) {
  22. _socketQueue = dispatch_queue_create("socketQueue", NULL);
  23. _listeningSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:_socketQueue];
  24. _connectedClients = [[NSMutableArray alloc] initWithCapacity:1];
  25. _port = port;
  26. _delegate = nil;
  27. }
  28. return self;
  29. }
  30. - (BOOL)startWithError:(NSError **)error
  31. {
  32. if (![self.listeningSocket acceptOnPort:self.port error:error]) {
  33. return NO;;
  34. }
  35. return YES;
  36. }
  37. - (void)stop
  38. {
  39. @synchronized(self.connectedClients) {
  40. for (NSUInteger i = 0; i < [self.connectedClients count]; i++) {
  41. [[self.connectedClients objectAtIndex:i] disconnect];
  42. }
  43. }
  44. [self.listeningSocket disconnect];
  45. }
  46. @end
  47. @implementation FBTCPSocket(AsyncSocket)
  48. - (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket
  49. {
  50. @synchronized(self.connectedClients) {
  51. [self.connectedClients addObject:newSocket];
  52. }
  53. [self.delegate didClientConnect:newSocket];
  54. }
  55. - (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
  56. {
  57. [self.delegate didClientSendData:sock];
  58. }
  59. - (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
  60. {
  61. @synchronized(self.connectedClients) {
  62. [self.connectedClients removeObject:sock];
  63. }
  64. [self.delegate didClientDisconnect:sock];
  65. }
  66. @end