FIRMessagingFakeSocket.m 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. * Copyright 2017 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import "FIRMessagingFakeSocket.h"
  17. #import "FIRMessagingConstants.h"
  18. #import "FIRMessagingDefines.h"
  19. @interface FIRMessagingSecureSocket() <NSStreamDelegate>
  20. @property(nonatomic, readwrite, assign) FIRMessagingSecureSocketState state;
  21. @property(nonatomic, readwrite, strong) NSInputStream *inStream;
  22. @property(nonatomic, readwrite, strong) NSOutputStream *outStream;
  23. @property(nonatomic, readwrite, assign) BOOL isInStreamOpen;
  24. @property(nonatomic, readwrite, assign) BOOL isOutStreamOpen;
  25. @property(nonatomic, readwrite, strong) NSRunLoop *runLoop;
  26. @end
  27. @interface FIRMessagingFakeSocket ()
  28. @property(nonatomic, readwrite, assign) int8_t bufferSize;
  29. @end
  30. @implementation FIRMessagingFakeSocket
  31. - (instancetype)initWithBufferSize:(uint8_t)bufferSize {
  32. self = [super init];
  33. if (self) {
  34. _bufferSize = bufferSize;
  35. }
  36. return self;
  37. }
  38. - (void)connectToHost:(NSString *)host
  39. port:(NSUInteger)port
  40. onRunLoop:(NSRunLoop *)runLoop {
  41. self.state = kFIRMessagingSecureSocketOpening;
  42. self.runLoop = runLoop;
  43. CFReadStreamRef inputStreamRef = nil;
  44. CFWriteStreamRef outputStreamRef = nil;
  45. CFStreamCreateBoundPair(NULL,
  46. &inputStreamRef,
  47. &outputStreamRef,
  48. self.bufferSize);
  49. self.inStream = CFBridgingRelease(inputStreamRef);
  50. self.outStream = CFBridgingRelease(outputStreamRef);
  51. if (!self.inStream || !self.outStream) {
  52. NSAssert(NO, @"Cannot create a fake socket");
  53. return;
  54. }
  55. self.isInStreamOpen = NO;
  56. self.isOutStreamOpen = NO;
  57. [self openStream:self.outStream];
  58. [self openStream:self.inStream];
  59. }
  60. - (void)openStream:(NSStream *)stream {
  61. NSAssert(stream, @"Cannot open nil stream");
  62. if (stream) {
  63. stream.delegate = self;
  64. [stream scheduleInRunLoop:self.runLoop forMode:NSDefaultRunLoopMode];
  65. [stream open];
  66. }
  67. }
  68. @end