GithubHelp home page GithubHelp logo

socket.io-objc's Introduction

The current version of this library does not support socket.io v1.0.
So if you want to use socket.io-objc, please fall back to v0.9.x.

Today (15/03/09) the Socket.io guys announced their own iOS library - grab it while it's still hot:
github.com/socketio/socket.io-client-swift


Socket.IO / Objective C Library

Interface to communicate between Objective C and Socket.IO with the help of websockets or Long-Polling. Originally based on fpotter's socketio-cocoa it uses other libraries/classes like

  • SocketRocket Look here for further instructions how to use/install SocketRocket.

Requirements

As of version 0.4, this library requires at least OS X 10.7 or iOS 5.0. Because of this, we were able to remove the external JSON frameworks in v0.5 and only rely on iOS' own NSJSONSerialization.

Usage

The easiest way to connect to your Socket.IO / node.js server is

SocketIO *socketIO = [[SocketIO alloc] initWithDelegate:self];
[socketIO connectToHost:@"localhost" onPort:3000];

If required, additional parameters can be included in the handshake by adding an NSDictionary to the withParams option:

[socketIO connectToHost:@"localhost"
                 onPort:3000
             withParams:@{@"auth_token":@"1234"}];

A namespace can also be defined in the connection details:

[socketIO connectToHost:@"localhost" onPort:3000 withParams:nil withNamespace:@"/users"];

There are different methods to send data to the server

- (void) sendMessage:(NSString *)data;
- (void) sendMessage:(NSString *)data withAcknowledge:(SocketIOCallback)function;
- (void) sendJSON:(NSDictionary *)data;
- (void) sendJSON:(NSDictionary *)data withAcknowledge:(SocketIOCallback)function;
- (void) sendEvent:(NSString *)eventName withData:(NSDictionary *)data;
- (void) sendEvent:(NSString *)eventName withData:(NSDictionary *)data andAcknowledge:(SocketIOCallback)function;

So you could send a normal Message like this

[socketIO sendMessage:@"hello world"];

or an Event (including some data) like this

NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:@"test1" forKey:@"key1"];
[dict setObject:@"test2" forKey:@"key2"];

[socketIO sendEvent:@"welcome" withData:dict];

If you want the server to acknowledge your Message/Event you would also pass a SocketIOCallback block

SocketIOCallback cb = ^(id argsData) {
    NSDictionary *response = argsData;
    // do something with response
};
[socketIO sendEvent:@"welcomeAck" withData:dict andAcknowledge:cb];

All delegate methods are optional - you could implement the following

- (void) socketIODidConnect:(SocketIO *)socket;
- (void) socketIODidDisconnect:(SocketIO *)socket disconnectedWithError:(NSError *)error;
- (void) socketIO:(SocketIO *)socket didReceiveMessage:(SocketIOPacket *)packet;
- (void) socketIO:(SocketIO *)socket didReceiveJSON:(SocketIOPacket *)packet;
- (void) socketIO:(SocketIO *)socket didReceiveEvent:(SocketIOPacket *)packet;
- (void) socketIO:(SocketIO *)socket didSendMessage:(SocketIOPacket *)packet;
- (void) socketIO:(SocketIO *)socket onError:(NSError *)error;

To process an incoming message or event just

// message delegate
- (void) socketIO:(SocketIO *)socket didReceiveMessage:(SocketIOPacket *)packet
{
    NSLog(@"didReceiveMessage >>> data: %@", packet.data);
}

// event delegate
- (void) socketIO:(SocketIO *)socket didReceiveEvent:(SocketIOPacket *)packet
{
    NSLog(@"didReceiveEvent >>> data: %@", packet.data);
}

Usage with OS X

Running the socket.io-objc library with OS X requires some minor changes:

  • you have to use the SocketRocket.framework for OSX instead of just the submodule
    see: SocketRocket's Installing OS X
    (best way I got this to work was as a subproject and I didn't have to add the "copy file" stuff)

  • when using the osx-framework, you have to fix the import-statement in SocketIOTransportWebsocket.h

// replace
#import SRWebSocket.h

// with
#import <SocketRocket/SRWebSocket.h>

Authors

Initial project by Philipp Kyeck http://beta-interactive.de.
Additional support from these amazing people.

License

(The MIT License)

Copyright (c) 2011-14 Philipp Kyeck http://beta-interactive.de

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

socket.io-objc's People

Contributors

antonholmquist avatar beepscore avatar bnadim avatar bridger avatar danlite avatar elwerene avatar hongkongkiwi avatar insanehunter avatar kayleg avatar mennopruijssers avatar michaelscaria avatar mralexgray avatar paiv avatar pkyeck avatar progeddog avatar psineur avatar revcbh avatar samlown avatar spesholized avatar taiyangc avatar yannickl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

socket.io-objc's Issues

Support for room chat

Hi pkyeck

Do you plan to support room chat, any time soon?

Kind regards
Leon Nguyen

Crashed when server side socket.io is dead

Firstly, thank you for your great library.

But, your library is crashed by index out of error, when server side socket died.
I'm now using socket.io (0.9.11) for node app, and in iOS side using your library (0.2.5) for connecting these two.

And then, if I stop the server side program with ctrl+c, then in client side crash happened at SocketIO.m. The problematic line is

_heartbeatTimeout = [[data objectAtIndex:1] floatValue];

I think you should check the index 1 is proper or not.

Thanks.

Crash while sending heartbeat when not using SBJson

When not using SBJson, I have a crash on the following line:

    // try Foundation's JSON coder, available in OS X 10.7/iOS 5.0
    serializer = NSClassFromString(@"NSJSONSerialization");
    if (serializer) {
        return [serializer JSONObjectWithData:data options:0 error:error];
    }

This is because the data is nill.

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'
*** First throw call stack:
(0x20ae052 0x1ba4d0a 0x2056a78 0x20569e9 0xe85fbd 0xb295 0xa7a4 0x3d70 0x6f78 0x691b 0x741a 0x9c7e 0x10313 0x1d7b3ec 0x1d7d515 0x1fe5833 0x1fe4db4 0x1fe4ccb 0x1f97879 0x1f9793e 0x460a9b 0x2a4d 0x2975 0x1)
terminate called throwing an exception

Backtrace:

#0  0x01ba4cde in objc_exception_throw ()
#1  0x02056a78 in +[NSException raise:format:arguments:] ()
#2  0x020569e9 in +[NSException raise:format:] ()
#3  0x00e85fbd in +[NSJSONSerialization JSONObjectWithData:options:error:] ()
#4  0x0000b295 in +[SocketIOJSONSerialization objectFromJSONData:error:] at ..../Vendor/socket.IO-objc/SocketIOJSONSerialization.m:62
#5  0x0000a7a4 in -[SocketIOPacket dataAsJSON] at..../Vendor/socket.IO-objc/SocketIO.m:844
#6  0x00003d70 in -[WebSocketController socketIO:didSendMessage:] at ..../lovepotion/Controller/WebSocketController.m:85
#7  0x00006f78 in -[SocketIO send:] at..../Vendor/socket.IO-objc/SocketIO.m:321
#8  0x0000691b in -[SocketIO sendHeartbeat] at ..../Vendor/socket.IO-objc/SocketIO.m:273
#9  0x0000741a in -[SocketIO onData:] at ..../Vendor/socket.IO-objc/SocketIO.m:371
#10 0x00009c7e in -[SocketIO webSocket:didReceiveMessage:] at ..../Vendor/socket.IO-objc/SocketIO.m:745
#11 0x00010313 in __30-[SRWebSocket _handleMessage:]_block_invoke_0 at ..../Vendor/SocketRocket/SocketRocket/SRWebSocket.m:727
#12 0x01d7b3ec in _dispatch_call_block_and_release ()
#13 0x01d7d515 in _dispatch_main_queue_callback_4CF ()
#14 0x01fe5833 in __CFRunLoopRun ()
#15 0x01fe4db4 in CFRunLoopRunSpecific ()
#16 0x01fe4ccb in CFRunLoopRunInMode ()
#17 0x01f97879 in GSEventRunModal ()
#18 0x01f9793e in GSEventRun ()
#19 0x00460a9b in UIApplicationMain ()

Server example?

Is there an example of creating a socket.io server and binding it to a port on the device? This would be useful for creating a javascript/native bridge in an app.

Not receiving messages from Server

I have a multi-platform node test server that will be used for several different things, but in this case the iOS app needs to receive a io.sockets.emit() and handle it. Currently, it connects and sets up a heartbeat just fine, as I can see it on my server's debug list. The server emits everything I throw at it but the didReceive* events are not being called by these emits. Here's my code:

  • (void)viewDidLoad
    {
    [super viewDidLoad];

    socket = [[SocketIO alloc] init];
    [socket connectToHost:@"*****************" onPort:XXX];
    }

  • (void) socket:(SocketIO *)socketIO didReceiveJSON:(SocketIOPacket *)packet
    {
    NSLog(@"didReceiveJSON() >>> data: %@", packet.data);
    }

  • (void) socket:(SocketIO *)socketIO didReceiveEvent:(SocketIOPacket *)packet
    {
    NSLog(@"didReceiveEvent() >>> data: %@", packet.data);
    }

  • (void) socket:(SocketIO *)socketIO didReceiveMessage:(SocketIOPacket *)packet
    {
    NSLog(@"didReceiveMessage() >>> data: %@", packet.data);
    }

Technically the server sends JSON but I wanted to cover all my bases. If there's any other code you might need, let me know.

** UPDATE - FIXED **

Was init like: socket = [[SocketIO alloc] init];
Had to set the delegate to itself like: socket = [[SocketIO alloc] initWithDelegate:self];

multiple namespace over just one socket connection.

Hi,

I have a socket server with web and iOS clients. And the socket server has multiple namespaces(game/chat/notification). I can connect to the server over one socket on web client by socket.io-client. The socket.id keeps same on each namespace connection to the server while using the web client. But the iOS client needs to create a new socket connection to connect each namespace. And I am having 3 socket connections with different socket.ids. I would like to decrease these socket connections to 1 just like the web client. Is it possible? Or I am on a wrong way?

Thanks in advance.

Acknowledgement with array parameter only uses first object

Hi!

I have a Socket.IO node.js server which acknowledges a message with an array as parameter:

socket.on('find', function (name, fn) {
    var objects = [
      {name: 'Isaias',   age: 21},
      {name: 'Raymundo', age: 22},
      {name: 'Americo',  age: 40}
    ];
    fn(objects);
  });

In Objective-C I have the following call:

[[self webSocket] sendEvent:@"find" withData:[NSDictionary dictionary] andAcknowledge:^(id argsData) {
    //argsData = first object of array.
}

ArgsData always is the first object of the array instead of the array.

I traced it back to SocketIO.m line 417:

                    if (argsStr && ![argsStr isEqualToString:@""]) {
                        argsData = [argsStr JSONValue];
                        if ([argsData count] > 0) {
                            argsData = [argsData objectAtIndex:0];
                        }
                    }

Is this as intended or a bug? Should I use a single object as parameter in the acknowledge function?

'message' is ignored by server

First, great work on updating the socket.IO library for v0.7.x!

I seemed to be sending messages and/or events fine and everything looks fine in the server debug console, but the socket.io server isn't registering that a message is received. Here is what i see in case you have any ideas.

debug - websocket received data packet 3:::tester message

part of server.js
// Create a Socket.IO instance, passing it our server
var socket = io.listen(server);

// Add a connect listener
socket.on('connection', function(client){

// Success! Now listen to messages to be received
client.on('message',function(event){
console.log('Received message from client!',event);
});

If server returns 503, crashes app

This library cannot parse an HTML return value, thus causing a crash.

<html><body><h1>503 Service Unavailable</h1>

Log:

2012-09-03 06:20:44.516 sbiphone[91009:f803] sid: <html><body><h1>503 Service Unavailable</h1>
No server is available to handle this request.
</body></html>
2012-09-03 06:20:44.516 sbiphone[91009:f803] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
*** First throw call stack:

I basically turned my server off and on again to see what would happen when socket.io didn't directly handle the request. Socket.IO-objc should gracefully handle these types of situations. I'd categorize this as a P1 type bug that makes the library unuseable in production.

Library does not support sending acknowledgments back to server

I've added support for this in my sandbox. If you'd like, I can push the changes or send you the modified files.

diff --git a/SocketIO.h b/SocketIO.h
index af5fede..b5521a9 100644
--- a/SocketIO.h
+++ b/SocketIO.h
@@ -71,6 +71,7 @@

  • (void) sendJSON:(NSDictionary *)data withAcknowledge:(SEL)function;

  • (void) sendEvent:(NSString *)eventName withData:(NSDictionary *)data;

  • (void) sendEvent:(NSString )eventName withData:(NSDictionary *)data andAcknowledge:(SEL)function;
    +- (void) sendAcknowledgement:(NSString
    )pId withArgs:(NSArray *)data;

    @EnD

@@ -83,6 +84,7 @@
NSString *name;
NSString *data;
NSArray *args;

  • NSString *endpoint;

@Private
NSArray *_types;
@@ -93,6 +95,7 @@
@Property (nonatomic, copy) NSString *ack;
@Property (nonatomic, copy) NSString *name;
@Property (nonatomic, copy) NSString *data;
+@Property (nonatomic, copy) NSString *endpoint;
@Property (nonatomic, copy) NSArray *args;

  • (id) initWithType:(NSString *)packetType;
    diff --git a/SocketIO.m b/SocketIO.m
    index 0b38c76..85d3402 100644
    --- a/SocketIO.m
    +++ b/SocketIO.m
    @@ -146,6 +146,15 @@
    [packet release];
    }

+- (void)sendAcknowledgement:(NSString *)pId withArgs:(NSArray *)data {

  • SocketIOPacket *packet = [[SocketIOPacket alloc] initWithType:@"ack"];
  • packet.data = [data JSONRepresentation];
  • packet.pId = pId;
  • packet.ack = @"data";
  • [self send:packet];
  • [packet release];
    +}

pragma mark -

pragma mark private methods

@@ -187,15 +196,26 @@
{
pId = [pId stringByAppendingString:@"+"];
}

  • [encoded addObject:pId];
  • // Do not write pid for acknowledgements
  • if ([type intValue] != 6) {
  •    [encoded addObject:pId];
    
  • }

// not yet sure what this is for
NSString *endPoint = @"";
[encoded addObject:endPoint];

  • if (packet.data != nil)
    {

  •    [encoded addObject:packet.data];
    
  •    NSString *ackpId = @"";
    
  •    // This is an acknowledgement packet, so, prepend the ack pid to the data
    
  •    if ([type intValue] == 6) {
    
  •        ackpId = [NSString stringWithFormat:@"%@%@", packet.pId, @"+"];
    
  •    }
    
  •    [encoded addObject:[NSString stringWithFormat:@":%@%@", ackpId, packet.data]];
    

    }

    NSString *req = [encoded componentsJoinedByString:@":"];
    @@ -240,8 +260,8 @@

     packet.pId = [result objectAtIndex:2];
    
  •    // 3 => ack
    
  •    // 4 => endpoint (TODO)  
    
  •    packet.ack = [result objectAtIndex:3];
    
  •    packet.endpoint = [result objectAtIndex:4];        
     packet.data = [result objectAtIndex:5];
    
     //
    

    @@ -546,7 +566,7 @@

    @implementation SocketIOPacket

-@synthesize type, pId, name, ack, data, args;
+@synthesize type, pId, name, ack, data, args, endpoint;

  • (id) init
    {
    @@ -614,6 +634,7 @@
    [ack release];
    [data release];
    [args release];

    • [endpoint release];

    [super dealloc];
    }

Consolidate with ARC-only version

I'm in the process of incorporating socket.IO-objc into our application, and I'm really liking it. One problem we have is we need to support systems that are not compatible with ARC (namely, i386 on OS X). Source-based libraries that are non-ARC are easy to use in ARC-based projects with the "-fno-objc-arc" flag. But, the opposite is not really possible. So, non-ARC is the best bet for us. But, it worries me that we may end up getting out of sync with the, what appears to be, main ARC-based repo.

What was the motivation for two repos, as opposed to either non-ARC-only, or ARC via conditional compilation? If it was just for speed-of-development, would you be up for either of these as a longer-term solution?

is socket.io v0.9 supported?

My server is running socket.io version 0.9

and I am using SRWebSocket, the handshake is successful, but upon reading a few stream, the input stream ended with this error: "The operation couldn’t be completed. Connection reset by peer"

and the bytes_read is -1.

attached is the log if necessary...

    (NSString *) $19 = 0x04c74520 GMjeomEm17E7J5BHQRuv:60:60:websocket,htmlfile,xhr-polling,jsonp-polling
    (lldb) po format
    (NSString *) $25 = 0x0002d6b0 wss://%@:%d/socket.io/1/websocket/%@
    (lldb) po url
    (id) $27 = 0x06976eb0 7:::1+0
    (lldb) po data
    (NSString *) $28 = 0x06976eb0 7:::1+0
    (lldb) po reason
    (NSString *) $29 = 0x0002e020 Stream end encountered

Thanks for the input!

How to 'socket.on'?

Well i have a webapplication where i just do this:

socket.on('0937afa17f4dc08f3c0e5dc908158370ce64df86', function (data) {
switch (data.handle) {
case 'new_chat':
var msg = data.name+" has started a new chat.";
reloadMenu();
newPlainNotification('New Chat', msg);
new_chat_sound.load();
new_chat_sound.play();
break;
}
}

but how can i do this with this framework. I managed to get the connection working and i can send messages to my server.

Problem with 'xhr-polling' transports protocol

Hi,

I've started to try socket.IO-objc yesterday, but I don't succeed in connecting successfully with our socket.io server.
Our socket.io server is on Heroku. And Heroku has created a ticket about socket.io (http://devcenter.heroku.com/articles/using-socket-io-with-node-js-on-heroku). They just authorise xhr-polling transport protocol.

So I have configured correctly my socket.io server.

My JavaScript client works normally, but the iOS client doesn't work. When I look the logs on the server, I see that socket.IO-objc try the connection still websocket protocol.

Example of NSLog Message :

2012-03-16 11:50:14.048 test_socket-io[719:707] Connecting to socket with URL: http://mysocket-server.com:80/socket.io/1/?t=16807
2012-03-16 11:50:17.089 test_socket-io[719:707] requestFinished() 1686486785637526742:15:25:xhr-polling
2012-03-16 11:50:17.091 test_socket-io[719:707] sid: 1686486785637526742
2012-03-16 11:50:17.092 test_socket-io[719:707] heartbeatTimeout: 22.000000
2012-03-16 11:50:17.093 test_socket-io[719:707] transports: (
"xhr-polling"
)
2012-03-16 11:50:17.098 test_socket-io[719:707] Opening ws://mysocket-server.com:80/socket.io/1/websocket/1686486785637526742
2012-03-16 11:50:42.191 test_socket-io[719:707] ERROR: Connection failed with error ... Read operation timed out
2012-03-16 11:50:42.193 test_socket-io[719:707] onDisconnect()

My socket.io server turn with v0.9.0.

help !!! what's wrong?

Opening ws://192.168.1.125:3737/socket.io/1/websocket/1279263871484575260
2012-06-09 10:53:11.858 NT[2251:207] -[**NSCFType getCFRunLoop]: unrecognized selector sent to instance 0x5710590
2012-06-09 10:53:11.860 NT[2251:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFType getCFRunLoop]: unrecognized selector sent to instance 0x5710590'
* Call stack at first throw:
(
0 CoreFoundation 0x01b45be9 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x01c9a5c2 objc_exception_throw + 47
2 CoreFoundation 0x01b476fb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187
3 CoreFoundation 0x01ab7366 __forwarding
+ 966
4 CoreFoundation 0x01ab6f22 _CF_forwarding_prep_0 + 50
5 NT 0x000e380e -[AsyncSocket attachStreamsToRunLoop:error:] + 94
6 NT 0x000e10c7 -[AsyncSocket setRunLoopModes:] + 1111
7 NT 0x002261ef -[WebSocket open] + 399
8 NT 0x002229da -[SocketIO openSocket] + 346
9 NT 0x002245e8 -[SocketIO requestFinished:] + 728
10 NT 0x001705dd -[ASIHTTPRequest reportFinished] + 173
11 Foundation 0x0151e9a6 __NSThreadPerformPerform + 251
12 CoreFoundation 0x01b2701f CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION + 15
13 CoreFoundation 0x01a8528b __CFRunLoopDoSources0 + 571
14 CoreFoundation 0x01a84786 __CFRunLoopRun + 470
15 CoreFoundation 0x01a84240 CFRunLoopRunSpecific + 208
16 CoreFoundation 0x01a84161 CFRunLoopRunInMode + 97
17 GraphicsServices 0x0226e268 GSEventRunModal + 217
18 GraphicsServices 0x0226e32d GSEventRun + 115
19 UIKit 0x00dbf42e UIApplicationMain + 1160
20 NT 0x000bce07 main + 135
21 NT 0x000027c5 start + 53
)
terminate called after throwing an instance of 'NSException'

warn - client not handshaken client should reconnect

When i disconnect from my socket i get this error warn - client not handshaken client should reconnect in the socket, i don't know why and where that error comes from? Can someone explain to me how i can solve it? Thanks in advance.

Can no longer connect

With commit SHA: f40d224 (removed NSURLConnection on main thread) I can no longer connect. Was working before, but now the only log message I get is

Connecting to socket with URL: http://#####:80/socket.io/1/?t=16807
Note: url masked, it is correctly printed in the log

I tried connecting when application becomes active, and using dispatch_async (which was working, both fail now)

Output from the server:

 debug - websocket writing 2::
[06/08 21:23:10 EDT]    debug - set heartbeat timeout for client 2077725512376673576
[06/08 21:23:10 EDT]    debug - got heartbeat packet
[06/08 21:23:10 EDT]    debug - cleared heartbeat timeout for client 2077725512376673576
[06/08 21:23:10 EDT]    debug - set heartbeat interval for client 2077725512376673576
[06/08 21:23:13 EDT]    debug - cleared heartbeat interval for client 2077725512376673576
[06/08 21:23:13 EDT]    debug - discarding transport
[06/08 21:23:12 EDT]    debug - emitting heartbeat for client 2077725512376673576
[06/08 21:23:12 EDT]    info  - transport end
[06/08 21:23:12 EDT]    debug - set close timeout for client 2077725512376673576
[06/08 21:23:12 EDT]    debug - cleared close timeout for client 2077725512376673576

Please add semantic version tags.

We’ve recently added socket.IO to the CocoaPods package manager repo.

CocoaPods is a tool for managing dependencies for OS X and iOS Xcode projects and provides a central repository for iOS/OS X libraries. This makes adding libraries to a project and updating them extremely easy and it will help users to resolve dependencies of the libraries they use.

However, socket.IO doesn't have any version tags. We’ve added the current HEAD as version 0.0.1, but a version tag will make dependency resolution much easier.

Semantic version tags (instead of plain commit hashes/revisions) allow for resolution of cross-dependencies.

In case you didn’t know this yet; you can tag the current HEAD as, for instance, version 1.0.0, like so:

$ git tag -a 1.0.0 -m "Tag release 1.0.0"
$ git push --tags

airplane mode then reconnect

i meet a problem: when i common enter my app,then connect the server,i can send message,all is ok

but when i press home and enter setting choice the airplane mode close the wifi, then open the wifi close the airplane mode. then enter my app, socket cannot connet,if i do other internet request for example download pic, the progressDialog is always show.

SSL Support

When enabling SSL I receive Socket closed by remote peer, which seems to come from GCDAsyncSocket.

On the server I get
info - handshake authorized 1616477163792068658 debug - client authorized

and then receive the closed error on the client

Websocket not getting connected.

Iam getting a error while trying to connect to websocket. The delegate 'webSocket:(WebSocket *)ws didFailWithError:(NSError *)error ' is fired with a null error. Can someone explain why I'm not able to connect?

modify port

hello i only modify NSString* kInsecureHandshakePortURL = @"http://%@:%d/socket.io/1/?t=%d%@" to
kInsecureHandshakePortURL = @"http://%@:%d/socket.io/1" because i modify server.if i use 80 port all is ok.but i use other port as "9082" .send event not succeed all ways. if i need to modify other ?

Crashes when containing object is deallocated with ARC

Because on disconnect a delegate is not set to nil I have experienced crashes when an object that contains SocketIO object is deallocated with ARC. To resolve I changed the code like this in SocketIO.m:

  • (void) disconnect
    {
    [self sendDisconnect];
    _delegate = nil; // crashes if not set to nil <<<------------------------------------------------
    }

  • (void) onDisconnect
    {
    [self log:@"onDisconnect()"];
    BOOL wasConnected = _isConnected;
    BOOL wasConnecting = _isConnecting;

    _isConnected = NO;
    _isConnecting = NO;
    _sid = nil;

    [_queue removeAllObjects];

    // Kill the heartbeat timer
    if (_timeout != nil) {
    [_timeout invalidate];
    _timeout = nil;
    }

    // Disconnect the websocket, just in case
    if (_webSocket != nil) {
    _webSocket.delegate = nil; //crashes if not set to nil <<<----------------------------
    [_webSocket close];
    }

    if ((wasConnected || wasConnecting)
    && [_delegate respondsToSelector:@selector(socketIODidDisconnect:)]) {
    [_delegate socketIODidDisconnect:self];
    }
    }

Correctly releasing SocketIO object (ARC library) in non-ARC project

I am using ARC version of the library in my non-ARC project. I am using the method explained in this tutorial to merge non-ARC project and ARC library. In this method the library is compiled as a static library (in ARC mode itself) and added as a second target to the project.

In my ViewController file I am initializing the socket using

SockIO *chatSockIO = [[SocketIO alloc] initWithDelegate:self];

and when I need to disconnect, I call

[chatSockIO disconnect];

which results socketIODidDisconnect delegate method to fire.

- (void) socketIODidDisconnect:(SocketIO *)socket{
   [chatSockIO release]; ==> is this call needed?
}

Now my question is about the line [chatSockIO release]. Should we need to release an object which itself is defined in ARC mode, but is used in a non-ARC project?

When I run this code with the line uncommented I am getting a crash saying,

-[SocketIO retain]: message sent to deallocated instance 0x6fec370

I tried run with zombies and it gave me the fully retain/release cycle of the sockIO object

#   Address     Category    Event Type  RefCt   Timestamp       Size    Responsible Library     Responsible Caller
0   0x72d5da0   SocketIO    Malloc      1       00:09.700.274   64      MyProject           -[MyViewController sendRequestForSocketIOPush]
1   0x72d5da0   SocketIO    Retain      2       00:09.700.317   0       MyProject           -[SocketIO initWithDelegate:]
2   0x72d5da0   SocketIO    Release     1       00:09.700.320   0       MyProject           -[SocketIO initWithDelegate:]
3   0x72d5da0   SocketIO    Retain      2       00:09.700.440   0       Foundation          -[NSURLConnectionInternal initWithInfo:]
4   0x72d5da0   SocketIO    Retain      3       00:10.413.717   0       Foundation          -[NSURLConnectionInternal _withConnectionAndDelegate:onlyActive:]
5   0x72d5da0   SocketIO    Release     2       00:10.413.761   0       Foundation          -[NSURLConnectionInternalConnection invokeForDelegate:]
6   0x72d5da0   SocketIO    Retain      3       00:10.413.797   0       Foundation          -[NSURLConnectionInternal _withConnectionAndDelegate:onlyActive:]
7   0x72d5da0   SocketIO    Release     2       00:10.413.811   0       Foundation          -[NSURLConnectionInternalConnection invokeForDelegate:]
8   0x72d5da0   SocketIO    Retain      3       00:10.413.816   0       Foundation          -[NSURLConnectionInternal _withConnectionAndDelegate:onlyActive:]
9   0x72d5da0   SocketIO    Release     2       00:10.415.087   0       Foundation          -[NSURLConnectionInternalConnection invokeForDelegate:]
10  0x72d5da0   SocketIO    Retain      3       00:10.415.214   0       Foundation          -[NSURLConnectionInternal _withConnectionAndDelegate:onlyActive:]
11  0x72d5da0   SocketIO    Release     2       00:10.415.216   0       Foundation          -[NSURLConnectionInternalConnection invokeForDelegate:]
12  0x72d5da0   SocketIO    Release     1       00:10.415.275   0       Foundation          -[NSURLConnectionInternalConnection invokeForDelegate:]
13  0x72d5da0   SocketIO    Retain      2       00:10.969.432   0       GraphicsServices    GSEventRunModal
14  0x72d5da0   SocketIO    Release     1       00:10.969.433   0       GraphicsServices    GSEventRunModal
15  0x72d5da0   SocketIO    Retain      2       00:10.969.434   0       GraphicsServices    GSEventRunModal
16  0x72d5da0   SocketIO    Release     1       00:10.969.456   0       GraphicsServices    GSEventRunModal
17  0x72d5da0   SocketIO    Retain      2       00:10.969.459   0       GraphicsServices    GSEventRunModal
18  0x72d5da0   SocketIO    Retain      3       00:10.969.488   0       Foundation          -[NSCFTimer initWithFireDate:interval:target:selector:userInfo:repeats:]
19  0x72d5da0   SocketIO    Release     2       00:10.976.115   0       MyProject           -[SocketIO setTimeout]
20  0x72d5da0   SocketIO    Retain      3       00:10.976.125   0       Foundation          -[NSCFTimer initWithFireDate:interval:target:selector:userInfo:repeats:]
21  0x72d5da0   SocketIO    Release     2       00:10.976.161   0       GraphicsServices    GSEventRunModal
22  0x72d5da0   SocketIO    Retain      3       00:13.935.328   0       GraphicsServices    GSEventRunModal
23  0x72d5da0   SocketIO    Release     2       00:13.935.373   0       MyProject           -[SocketIO setTimeout]
24  0x72d5da0   SocketIO    Retain      3       00:13.935.399   0       Foundation          -[NSCFTimer initWithFireDate:interval:target:selector:userInfo:repeats:]
25  0x72d5da0   SocketIO    Release     2       00:13.935.685   0       MyProject           -[SocketIO onDisconnect]
26  0x72d5da0   SocketIO    Release     1       00:13.935.705   0       MyProject           -[MyViewController socketIODidDisconnect:]
27  0x72d5da0   SocketIO    Release     0       00:13.935.716   0       GraphicsServices    GSEventRunModal
28  0x72d5da0   SocketIO    Zombie      -1      00:13.936.298   0       GraphicsServices    GSEventRunModal

To check I commented the [chatSockIO release] line and put a log in dealloc function of SocketIO class. When I run there is no crash, but dealloc is not getting called and Allocations instrument shows memory is not getting released.

- (void) socketIODidDisconnect:(SocketIO *)socket{
   //[chatSockIO release];   //==> is this call needed?
}
- (void) dealloc
{
    NSLog(@"dealloc of socketio");
    _host = nil;
    _sid = nil;
    _endpoint = nil;

    _webSocket = nil;

    [_timeout invalidate];
    _timeout = nil;

    _queue = nil;
    _acks = nil;
}

So how to release socketIO class in a non-ARC project?

Note : Yesterday I asked the same question on a generic way in stackoverflow. But no one was able to answer.

EXC_BAD_ACCESS in SocketIO.m -onData

I occasionally and randomly get an EXC_BAD_ACCESS around line 398 in SocketIO.M. That line reads:

if ([_delegate respondsToSelector:@selector(socketIO:didReceiveEvent:)]) {

Most of the time it works great, but the few random times are bad news if it crashes my app. :( Any suggestions on helping track down the problem?

Reconnect event missing(?)

In my desktop browser socket.io js implementation, the client seems to be intelligent enough to reconnect and grab the old socket in the case that the socket server restarts or something like that.

Before I change my server side code to not rely on this socket id persistence, I wanted to ask if I was missing something with this excellent library.

Trying to get socket.IO-objc to work with socket.io's chat example

I am using socket.io's chat example, and I can receive messages. However, I can't send messages. While attempting to set the nickname, I get a crash on the node instance.

On the iOS side, I send a message in the socketDidConnect method after my viewDidLoad method...

  • (void)viewDidLoad
    {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.socketIO = [[SocketIO alloc] initWithDelegate:self];
    self.socketIO.useSecure = NO;

    [self.socketIO connectToHost:@"localhost" onPort:3000];
    }

  • (void) socketIODidConnect:(SocketIO *)socket{
    NSLog(@"We connected....");
    [self.socketIO sendEvent:@"nickname" withData:@"iPhone"];
    }

This triggers the fn(false) statement in the app.js file which cause the following crash:

/Users/steffenfrost/Documents/Workspace/nodeTutorial/app.js:73
fn(false); // add it to array of nicknames and broadcast i
^
TypeError: undefined is not a function
at Socket. (/Users/steffenfrost/Documents/Workspace/nodeTutorial/app.js:73:7)
at Socket.EventEmitter.emit as $emit
at SocketNamespace.handlePacket (/Users/steffenfrost/Documents/Workspace/nodeTutorial/node_modules/socket.io/lib/namespace.js:335:22)
at Manager.onClientMessage (/Users/steffenfrost/Documents/Workspace/nodeTutorial/node_modules/socket.io/lib/manager.js:487:38)
at WebSocket.Transport.onMessage (/Users/steffenfrost/Documents/Workspace/nodeTutorial/node_modules/socket.io/lib/transport.js:387:20)
at Parser. (/Users/steffenfrost/Documents/Workspace/nodeTutorial/node_modules/socket.io/lib/transports/websocket/hybi-16.js:39:10)
at Parser.EventEmitter.emit (events.js:88:17)
at opcodeHandlers.1.finish (/Users/steffenfrost/Documents/Workspace/nodeTutorial/node_modules/socket.io/lib/transports/websocket/hybi-16.js:288:16)
at Parser.opcodeHandlers.1.expectData as expectHandler
at Parser.add (/Users/steffenfrost/Documents/Workspace/nodeTutorial/node_modules/socket.io/lib/transports/websocket/hybi-16.js:466:24)

I found some discussion as to the meaning of the fn() call here:
http://stackoverflow.com/questions/7718979/meaning-of-fn-in-the-socket-io-chat-sample-code

Having a hard time because I am weak on JS.

Hilfe! Someone help please.

ARC

Please use ARC (Automatic Reference Counting).

The library is only for MAC OS

Please indicate that it is only for mac os , doesn't work for iOS . "Objective C library" IS TO CORRECT ! Its have to be "Mac OS library"

Callback not launching async.

I attempt to send an event with a callback inside an async block like this:

dispatch_async(networkQueue, ^(){ 
    __block NSString * ret;
    [self registerWithUsername:@"sfasf" email:@"[email protected]" password:@"asfa  324" callbackHandler:^(NSString * result){
        ret = result;
        NSLog(@"async dispatdh");
        NSLog(ret);
    }];      
});

-(void)registerWithUsername:(NSString *) name email:(NSString *) email password:(NSString *) password callbackHandler: (void(^)(NSString * result)) handler{
NSLog(@"register ---");
NSLog(@"%@", [NSThread currentThread]);
if (netConnection.isConnected){

    NSDictionary * registerData = [NSDictionary dictionaryWithObjectsAndKeys:name, @"username", email, @"email", password, @"password", nil];
    [netConnection sendEvent:@"register" withData:registerData andAcknowledge:^(id argsData) {
        NSString * rspData;
        NSLog(@"callback --");
        NSLog(@"%@", [NSThread currentThread]);

        NSDictionary * response = argsData;
        rspData = [[[response objectForKey:@"data"] objectForKey:@"message"] objectForKey:@"password"];
        dispatch_async(dispatch_get_main_queue(), ^{handler(rspData);});
    }];
}
}

But the callback block never gets invoked. If I call the function normally it works well.
Is there any way to fix this, because I think running the network operations on a separate queue will make many peoples' lives very easy.

Many crashes after disconnection. What's the best way?

On my ARC project I use socket.io just on a Map ViewController which the user can reach after pushing some ViewControllers. So I set this VC as SocketIODelegate and declared a SocketIO instance on it.

It worked fine until I pop the ViewController and disconnect SocketIO on viewWillDissappear. I had several random chashes which led me to understand that the SocketIO instance and delegate where being freed before the right time.

So I set the SocketIO instance as "global" on another custom class and created a NSObject class only to be the SocketIODelegate and both will never die in memory.

It seemed to have helped to avoid some crashes but I still get some of them on disconnecting mainly on these lines (always EXC_BAD_ACCESS):

SocketIO.m: [self onDisconnect:[NSError errorWithDomain:SocketIOError code:SocketIOServerRespondedWithDisconnect userInfo:nil]];

SocketIO.m: if ([_delegate respondsToSelector:@selector(socketIODidDisconnect:disconnectedWithError:)]) {

SocketIOTransportWebsocket.m: [delegate onDisconnect:[NSError errorWithDomain:SocketIOError code:SocketIOWebSocketClosed userInfo:nil]];

SRWebSocket.m: [self.delegate webSocket:self didCloseWithCode:0 reason:@"Stream end encountered" wasClean:NO];

Also en every disconnect I get:
Error Domain=SocketIOError Code=-2 "The operation couldn’t be completed. (SocketIOError error -2.)"

Whats the right way to use it in my case?

Thanks in advance!

Reading data from "data.packetAsJSON

When i'm trying to extract all the data from the object it not gives me the correct value, my code looks like this:

NSMutableArray *receivedData = [packet.dataAsJSON valueForKeyPath:@"args"];
NSString *handle = [receivedData valueForKeyPath:@"handle"];
NSLog(@"%@", handle);

The NSLog shows this for the handle:
2013-01-10 19:17:45.551 SupLive[] "new_visitor"

Why does it returns something like that and not just new_visitor?

The NSLog for the receivedData is:
2013-01-10 19:24:10.230 SupLive[]
"amount_visits" = 10;
browser = "Google Chrome";
"company_id" = 1;
handle = "new_visitor";
"user_agent" = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.101 Safari/537.11";

Unable to Successfully Connect

Hello,

Whenever I create a connection to my socket.io server, I receive the following error in SocketIO.m:

  - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
      [_httpRequestData setLength:0];
  }

Thread 1: EXC_BAD_ACCESS (code=1, address=0x10000008)

Am I doing something improperly? I've simply connected with the following:

    [socketIO connectToHost:@"localhost" onPort:3000];

Here's xCode's output:

2012-06-03 14:57:12.261 TheGame[76703:11603] Connecting to socket with URL: http://localhost:3000/socket.io/1/?t=16807
2012-06-03 14:57:12.269 TheGame[76703:11603] -[UITouchData setLength:]: unrecognized selector sent to instance 0x7a8b5e0
2012-06-03 14:57:12.270 TheGame[76703:11603] *** Terminating app due to uncaught exception     'NSInvalidArgumentException', reason: '-[UITouchData setLength:]: unrecognized selector sent to instance 0x7a8b5e0'
*** First throw call stack:
(0x13da022 0x172ecd6 0x13dbcbd 0x1340ed0 0x1340cb2 0x6c25 0x105bb50 0x1059e84 0x105aea7 0x1059e3f 0x1059fc5 0xf9e5bb 0xae887 0x17c710 0x17c861 0xa6120 0x17c117 0xa5fbf 0x13ae94f 0x1311b43 0x1311424 0x1310d84 0x1310c9b 0x20657d8 0x206588a 0x658626 0x20e2 0x2055 0x1)
terminate called throwing an exception(lldb) 

And here's confirmation that the connection is being made from the socket.io server:

info  - socket.io started
debug - client authorized
info  - handshake authorized 1062063227742906142

Thanks,
Michael

Complete Source Code for Testing

Hi pkyeck

Could you post your completed project source code for testing here? I had such a hard time finding all the required libraries and got them up and running.

Thank you so much

Kind regards

SRWebSocket receives response bot does not dispatch to delegate

In the function _handleMessage: I can see a response message from the server, but the code inside dispatch_async is not executed and thus the function webSocket:didReceiveMessage: isn't.
This doesn't occur in other cases I send messages to server. What might be wrong in this specific case?

namespacing a socket

Hi pkyeck,

I have the code like this on the server side:

var socketio = require('socket.io').listen(server).of('/ns');

and the code like this on the client side (javascript):

io.connect('http://localhost:8080/ns');

It seems like namespacing a socket isn't supported yet by socket.IO-objc library. There is possibility to specify just host and port at the moment. Do you have plans to add support for this feature?

thanks,
-bsnote

how to call didReceiveEvent when my app DidEnterBackground

hello,at present my app not ReceiveEvent when my appDidEnterBackground,but when my app at front it give me event. how to use - (void) socketIO:(SocketIO *)socket didReceiveEvent:(SocketIOPacket *)packet method,it can also receive event when my app DidEnterBackground.

if you can give more detail demo,your demo is very easy,you can also add check socket connect and rebuild connect and so on

Server not receiving messages

So my server and application connect successfully. And my server can successfully send messages to the client. However the ios app's message do not get registered by the server. Any ideas what could be causing this?

Server:

var io = require('socket.io').listen(server);

io.sockets.on('connection', function (socket) {
  console.log("CONNECTED!");
  socket.emit('Hello from the server');
});

io.sockets.on('mapReady', function() {
  console.log("Received mapsReady");
});

Client:

- (void) _reconnect {
    NSLog(@"Connecting....");
    [socketio connectToHost:@"[domain].jit.su" onPort:80];
}

- (void) socketIO:(SocketIO *)socket didReceiveEvent:(SocketIOPacket *)packet {
    NSLog(@"didReceiveEvent() >>> data: %@", packet.data);
}

- (void) socketIO:(SocketIO *)socket didReceiveJSON:(SocketIOPacket *)packet {
    NSLog(@"Received JSON");
}

- (void) socketIO:(SocketIO *)socket didReceiveMessage:(SocketIOPacket *)packet {
    NSLog(@"didReceiveMessage() >>> data: %@", packet.data);
}

- (void) socketIO:(SocketIO *)socket didSendMessage:(SocketIOPacket *)packet {
    NSLog(@"Sent message");
}

- (void) socketIO:(SocketIO *)socket failedToConnectWithError:(NSError *)error {
    NSLog(@"Failed to connect");
}

- (void) socketIODidConnect:(SocketIO *)socket {
    NSLog(@"Connected!");
    [socketio sendEvent:@"mapsReady" withData:nil];
}

- (void) socketIODidDisconnect:(SocketIO *)socket {
    NSLog(@"Disconnected");
}

- (void) socketIOHandshakeFailed:(SocketIO *)socket {
    NSLog(@"Handshake failed");
}

Payloads cause disconnects (solution provided as gist)

Normally I would submit a pull request, however since my version of the code is so out of date (prior to when long-polling and ARC were supported), I thought I'd send it along as an issue instead.

Every once in a while (during heavy socket traffic), the server can decide to send a payload where multiple packets are returned in a single poll response (if using xhr-polling, for example). They are separated by the \ufffd character, and include the byte length of each packet, like:

�[packet_0 length]�[packet_0]�[packet_1 length]�[packet_1]�[packet_n length]�[packet_n]

Currently, I believe onData merely handles the data as a single packet, but there are cases when the server sends multiple packets in a single response.

I wrote some code where you can pass the data NSString from onData and it returns to you an NSArray of individual messages: https://gist.github.com/4480663

The rest of the parsing can be the same. Hope that is useful!

How to disconnect properly?

I cannot manually emit the event "disconnect" since it is reserved. But when my app goes into the background or inactive, I need to disconnect the socket. So what I did was create a "manual_disconnect" method to pretty much do the same which I could call myself.

Is this totally wrong? Does this library call the built in disconnect event on its own or is there a way to do it?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.