MBWebSocketServer icon indicating copy to clipboard operation
MBWebSocketServer copied to clipboard

Ability to send only to specific connection(s)

Open hongkongkiwi opened this issue 13 years ago • 1 comments

Depending on how the server is used, it sometimes only needs to deal with specific connections. For example, disconnect a specific connection or send data to a specific connection(s).

In my case I was having the server manage sessions which clients could join/leave. So I added the following (very simple) code.

// MBWebSocketServer.h
- (void)disconnectConnection:(GCDAsyncSocket *)aConnection;
- (void)sendToConnection:(GCDAsyncSocket *)aConnection data:(id)object;
- (void)sendToConnections:(NSArray *)aCollectionsArray data:(id)object;

// MBWebSocketServer.m
- (void)sendToConnection:(GCDAsyncSocket *)aConnection data:(id)object {
    NSData *payload = [object webSocketFrameData];
    [aConnection writeData:payload withTimeout:-1 tag:3];
}

- (void)sendToConnections:(NSArray *)aCollectionsArray data:(id)object {
    id payload = [object webSocketFrameData];
    for (GCDAsyncSocket *connection in aCollectionsArray) {
        [connection writeData:payload withTimeout:-1 tag:3];
    }
}

- (void)disconnectConnection:(GCDAsyncSocket *)aConnection {
    [aConnection disconnect];
}

hongkongkiwi avatar Dec 18 '12 03:12 hongkongkiwi

Current master has:

- (void)webSocketServer:(MBWebSocketServer *)webSocket didReceiveData:(NSData *)data fromConnection:(GCDAsyncSocket *)connection;

You can then send data to that GCDAsyncSocket provided it is formatted correctly first. I provide the webSocketFrameData method on various types of object for that purpose.

A little convoluted but it's more flexible which suited my usage.

mxcl avatar Mar 08 '13 18:03 mxcl