IOS Streaming Browser 1.0
An IOS streaming browser to stream the display to others or to a projector

WebSocket Class Reference

#import <WebSocket.h>

Collaboration diagram for WebSocket:

Public Member Functions

(id) - initWithRequest:socket:
(void) - start
(void) - stop
(void) - sendMessage:
(void) - didOpen
(void) - didReceiveMessage:
(void) - didClose
(void) - readRequestBody
(void) - sendResponseBody
(void) - sendResponseHeaders

Static Public Member Functions

(BOOL) + isWebSocketRequest:

Protected Attributes

HTTPMessagerequest
GCDAsyncSocketasyncSocket
NSDataterm
BOOL isStarted
BOOL isOpen
BOOL isVersion76

Properties

id delegate
dispatch_queue_t websocketQueue

Detailed Description

Definition at line 9 of file WebSocket.h.


Member Function Documentation

- (void) didClose

If the web socket did close

Notifiy delegate that websocket did close

Definition at line 642 of file WebSocket.m.

{
        
        // Override me to perform any cleanup when the socket is closed
        // This method is invoked on the websocketQueue.
        // 
        // Don't forget to invoke [super didClose] at the end of your method.
        
        // Notify delegate that the websocket did close
        if ([delegate respondsToSelector:@selector(webSocketDidClose:)])
        {
        
                [delegate webSocketDidClose:self];
        }
        
        // Notify HTTPServer
        [[NSNotificationCenter defaultCenter] postNotificationName:WebSocketDidDieNotification object:self];
}
- (void) didOpen

Subclass API

These methods are designed to be overriden by subclasses. If the web socket did open

If the web socket has been opened

Definition at line 572 of file WebSocket.m.

{
        
        // Override me to perform any custom actions once the WebSocket has been opened.
        // This method is invoked on the websocketQueue.
        // 
        // Don't forget to invoke [super didOpen] in your method.
        
        // Start reading for messages
        [asyncSocket readDataToLength:1 withTimeout:TIMEOUT_NONE tag:TAG_PREFIX];
        
        // Notify delegate that the web socket did open
        if ([delegate respondsToSelector:@selector(webSocketDidOpen:)])
        {
        
                [delegate webSocketDidOpen:self];
        }
}
- (void) didReceiveMessage: (NSString *)  msg

If the web socket did receive an incoming message

Did receive an incoming message param NSString

Definition at line 622 of file WebSocket.m.

                         :(NSString *)msg
{
        
        // Override me to process incoming messages.
        // This method is invoked on the websocketQueue.
        // 
        // For completeness, you should invoke [super didReceiveMessage:msg] in your method.
        
        // Notify delegate that it did receive a message
        if ([delegate respondsToSelector:@selector(webSocket:didReceiveMessage:)])
        {
        // Notify the socket it received a message
                [delegate webSocket:self didReceiveMessage:msg];
        }
}
- (id) initWithRequest: (HTTPMessage *)  aRequest
socket: (GCDAsyncSocket *)  socket 

Initialize with HTTPMessage request and a socket param HTTPMessage param GCDAsyncSocket

Initialize the web socket with an HTTP request and a socket param HTTPMessage param GCDAsyncSocket returns id

Definition at line 151 of file WebSocket.m.

                     :(HTTPMessage *)aRequest socket:(GCDAsyncSocket *)socket
{
        // If the http request is not nil
        if (aRequest == nil)
        {
                [self release];
                return nil;
        }
        
    // If the http request is nil
    
    
        if ((self = [super init]))
        {
                // Creates a new dispatch queue to which blocks may be submitted
                websocketQueue = dispatch_queue_create("WebSocket", NULL);
                request = [aRequest retain];
                
                asyncSocket = [socket retain];
        
        // Set this web socket instance as the asyncSocket delegate, and the websocketQueue as the delegate queue
                [asyncSocket setDelegate:self delegateQueue:websocketQueue];

                // Set the flag for whether the socket is open
                isOpen = NO;
        
        // Get whether this request is a version 76 web socket compliant
                isVersion76 = [[self class] isVersion76Request:request];
                
        // Creates a terminator
                term = [[NSData alloc] initWithBytes:"\xFF" length:1];
        }
        return self;
}
+ (BOOL) isWebSocketRequest: (HTTPMessage *)  request

Class method param HTTPMessage returns BOOL

Whether the HTTPRequest is a request for a web socket param HTTPMessage returns BOOL

Definition at line 51 of file WebSocket.m.

                          :(HTTPMessage *)request
{
        // Request (Draft 75):
        // 
        // GET /demo HTTP/1.1
        // Upgrade: WebSocket
        // Connection: Upgrade
        // Host: example.com
        // Origin: http://example.com
        // WebSocket-Protocol: sample
        // 
        // 
        // Request (Draft 76):
        //
        // GET /demo HTTP/1.1
        // Upgrade: WebSocket
        // Connection: Upgrade
        // Host: example.com
        // Origin: http://example.com
        // Sec-WebSocket-Protocol: sample
        // Sec-WebSocket-Key1: 4 @1  46546xW%0l 1 5
        // Sec-WebSocket-Key2: 12998 5 Y3 1  .P00
        // 
        // ^n:ds[4U
        
        // Look for Upgrade: and Connection: headers.
        // If we find them, and they have the proper value,
        // we can safely assume this is a websocket request.
        
    // Gets the Upgrade header value from the request
        NSString *upgradeHeaderValue = [request headerField:@"Upgrade"];
    
    // Gets the Connection header value from the request
        NSString *connectionHeaderValue = [request headerField:@"Connection"];
        
    
    
        BOOL isWebSocket = YES;
        
    // Check if there is an upgrade and connection value.  If the header doesn't have an upgrade and connection header, then it is not a web-socket request
        if (!upgradeHeaderValue || !connectionHeaderValue) {
                isWebSocket = NO;
        } // Make sure the upgrade header value is 'WebSocket'
        else if (![upgradeHeaderValue caseInsensitiveCompare:@"WebSocket"] == NSOrderedSame) {
                isWebSocket = NO;
        } // Make sure the connection header value is 'Upgrade'
        else if (![connectionHeaderValue caseInsensitiveCompare:@"Upgrade"] == NSOrderedSame) {
                isWebSocket = NO;
        }
        
        // return that this request is a web socket request
        return isWebSocket;
}
- (void) readRequestBody

Read the http request body

- (void) sendMessage: (NSString *)  msg

Public API

Sends a message over the WebSocket. This method is thread-safe.

Sends a message param NSString

Definition at line 595 of file WebSocket.m.

                   :(NSString *)msg
{
        // Encodes the message
        NSData *msgData = [msg dataUsingEncoding:NSUTF8StringEncoding];
        
    // Puts message into a NSMutableData
        NSMutableData *data = [NSMutableData dataWithCapacity:([msgData length] + 2)];
        
    
        [data appendBytes:"\x00" length:1];  // NULL 0x00

        [data appendData:msgData];

    
        [data appendBytes:"\xFF" length:1];  // End of transmission 0x04

        
        // Remember: GCDAsyncSocket is thread-safe
        
    // Writes data to the socket with no timeout or tag
        [asyncSocket writeData:data withTimeout:TIMEOUT_NONE tag:0];
}
- (void) sendResponseBody

Send a response body

- (void) sendResponseHeaders

Send the response headers

- (void) start

Public API

These methods are automatically called by the HTTPServer. You may invoke the stop method yourself to close the WebSocket manually. Starting point for the WebSocket after it has been fully initialized (including subclasses). This method is called by the HTTPConnection it is spawned from.

Starting point for the WebSocket after it has been fully initialized (including subclasses). This method is called by the HTTPConnection it is spawned from.

Definition at line 246 of file WebSocket.m.

{
        // This method is not exactly designed to be overriden.
        // Subclasses are encouraged to override the didOpen method instead.
        
    // Submits a block for asynchronous execution on the websocketQueue
        dispatch_async(websocketQueue, ^{
        
                NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
                
        // If the websocket is started
                if (isStarted) return;
        
        // Sets web socket flag to started
                isStarted = YES;
                
        // if the request is version 76 compliant
                if (isVersion76)
                {
            // Read the request body
                        [self readRequestBody];
                }
                else // if the request is not version 76 compliant
                {
            // Set response headers
                        [self sendResponseHeaders];
            
            // if web socket has been opened
                        [self didOpen];
                }
                
                [pool release];
        }); // END OF BLOCK
}
- (void) stop

This method is called by the HTTPServer if it is asked to stop. The server, in turn, invokes stop on each WebSocket instance.

Definition at line 285 of file WebSocket.m.

{
        // This method is not exactly designed to be overriden.
        // Subclasses are encouraged to override the didClose method instead.
        
    // Submits a block for asynchronous execution on the websocketQueue
        dispatch_async(websocketQueue, ^{
        
                NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
                
                [asyncSocket disconnect];
                
                [pool release];
        
        }); // END OF BLOCK
}

Field Documentation

- (GCDAsyncSocket*) asyncSocket [protected]

the socket (i.e. file handle)

Definition at line 25 of file WebSocket.h.

- (BOOL) isOpen [protected]

if web socket is open

Definition at line 40 of file WebSocket.h.

- (BOOL) isStarted [protected]

if web socket is started

Definition at line 35 of file WebSocket.h.

- (BOOL) isVersion76 [protected]

if version76

Definition at line 45 of file WebSocket.h.

- (HTTPMessage*) request [protected]

the web socket request

Definition at line 20 of file WebSocket.h.

- (NSData*) term [protected]

Definition at line 30 of file WebSocket.h.


Property Documentation

- (id) delegate [read, write, assign]

Delegate option.

In most cases it will be easier to subclass WebSocket, but some circumstances may lead one to prefer standard delegate callbacks instead.

Get the websocket delegate returns id

Definition at line 68 of file WebSocket.h.

- (dispatch_queue_t) websocketQueue [read, assign]

websocket queue

The WebSocket class is thread-safe, generally via it's GCD queue. All public API methods are thread-safe, and the subclass API methods are thread-safe as they are all invoked on the same GCD queue.

Definition at line 15 of file WebSocket.h.


The documentation for this class was generated from the following files:
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Properties Defines