Browse Source

Give the delegate the ability to specify whether SRWebSocket should convert NSData to NSString for TEXT messages. This is an optimization for when the server is sending text serialized as JSON. In this case we would turn the string back into NSData before passing it to NSJSONSerialization, which removes 2 data <--> string conversions.

Peter Meyers 9 years ago
parent
commit
ad3ad77909
2 changed files with 15 additions and 9 deletions
  1. 3 0
      SocketRocket/SRWebSocket.h
  2. 12 9
      SocketRocket/SRWebSocket.m

+ 3 - 0
SocketRocket/SRWebSocket.h

@@ -124,6 +124,9 @@ extern NSString *const SRHTTPResponseErrorKey;
 - (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean;
 - (void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload;
 
+// Return YES to convert messages sent as Text to an NSString. Return NO to skip NSData -> NSString conversion for Text messages. Defaults to YES.
+- (BOOL)webSocketShouldConvertTextFrameToString:(SRWebSocket *)webSocket;
+
 @end
 
 #pragma mark - NSURLRequest (SRCertificateAdditions)

+ 12 - 9
SocketRocket/SRWebSocket.m

@@ -938,16 +938,19 @@ static inline BOOL closeCodeIsValid(int closeCode) {
     //otherwise there can be misbehaviours when value at the pointer is changed
     switch (opcode) {
         case SROpCodeTextFrame: {
-            NSString *str = [[NSString alloc] initWithData:frameData encoding:NSUTF8StringEncoding];
-            if (str == nil && frameData) {
-                [self closeWithCode:SRStatusCodeInvalidUTF8 reason:@"Text frames must be valid UTF-8"];
-                dispatch_async(_workQueue, ^{
-                    [self closeConnection];
-                });
-
-                return;
+            if ([self.delegate respondsToSelector:@selector(webSocketShouldConvertTextFrameToString:)] && ![self.delegate webSocketShouldConvertTextFrameToString:self]) {
+                [self _handleMessage:[frameData copy]];
+            } else {
+                NSString *str = [[NSString alloc] initWithData:frameData encoding:NSUTF8StringEncoding];
+                if (str == nil && frameData) {
+                    [self closeWithCode:SRStatusCodeInvalidUTF8 reason:@"Text frames must be valid UTF-8"];
+                    dispatch_async(_workQueue, ^{
+                        [self closeConnection];
+                    });
+                    return;
+                }
+                [self _handleMessage:str];
             }
-            [self _handleMessage:str];
             break;
         }
         case SROpCodeBinaryFrame: