GithubHelp home page GithubHelp logo

facebookincubator / socketrocket Goto Github PK

View Code? Open in Web Editor NEW
9.5K 334.0 2.0K 2.38 MB

A conforming Objective-C WebSocket client library.

License: Other

Makefile 0.40% Objective-C 93.61% Ruby 0.59% Go 0.83% Python 1.24% HTML 0.42% JavaScript 1.51% Shell 0.68% C 0.72%

socketrocket's Introduction

SocketRocket

Platforms License

Podspec Carthage Compatible

Build Status

A conforming WebSocket (RFC 6455) client library for iOS, macOS and tvOS.

Test results for SocketRocket here. You can compare to what modern browsers look like here.

SocketRocket currently conforms to all core ~300 of Autobahn's fuzzing tests (aside from two UTF-8 ones where it is merely non-strict tests 6.4.2 and 6.4.4).

Features/Design

  • TLS (wss) support, including self-signed certificates.
  • Seems to perform quite well.
  • Supports HTTP Proxies.
  • Supports IPv4/IPv6.
  • Supports SSL certificate pinning.
  • Sends ping and can process pong events.
  • Asynchronous and non-blocking. Most of the work is done on a background thread.
  • Supports iOS, macOS, tvOS.

Installing

There are a few options. Choose one, or just figure it out:

Add the following line to your Podfile:

pod 'SocketRocket'

Run pod install, and you are all set.

Add the following line to your Cartfile:

github "facebook/SocketRocket"

Run carthage update, and you should now have the latest version of SocketRocket in your Carthage folder.

  • Using SocketRocket as a sub-project

    You can also include SocketRocket as a subproject inside of your application if you'd prefer, although we do not recommend this, as it will increase your indexing time significantly. To do so, just drag and drop the SocketRocket.xcodeproj file into your workspace.

API

SRWebSocket

The Web Socket.

Note:

SRWebSocket will retain itself between -(void)open and when it closes, errors, or fails. This is similar to how NSURLConnection behaves (unlike NSURLConnection, SRWebSocket won't retain the delegate).

Interface

@interface SRWebSocket : NSObject

// Make it with this
- (instancetype)initWithURLRequest:(NSURLRequest *)request;

// Set this before opening
@property (nonatomic, weak) id <SRWebSocketDelegate> delegate;

// Open with this
- (void)open;

// Close it with this
- (void)close;

// Send a Data
- (void)sendData:(nullable NSData *)data error:(NSError **)error;

// Send a UTF8 String
- (void)sendString:(NSString *)string error:(NSError **)error;

@end

SRWebSocketDelegate

You implement this

@protocol SRWebSocketDelegate <NSObject>

@optional

- (void)webSocketDidOpen:(SRWebSocket *)webSocket;

- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessageWithString:(NSString *)string;
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessageWithData:(NSData *)data;

- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error;
- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(nullable NSString *)reason wasClean:(BOOL)wasClean;

@end

Testing

Included are setup scripts for the python testing environment. It comes packaged with vitualenv so all the dependencies are installed in userland.

To run the short test from the command line, run:

  make test

To run all the tests, run:

  make test_all

The short tests don't include the performance tests (the test harness is actually the bottleneck, not SocketRocket).

The first time this is run, it may take a while to install the dependencies. It will be smooth sailing after that.

You can also run tests inside Xcode, which runs the same thing, but makes it easier to debug.

  • Choose the SocketRocketTests target
  • Make sure your running destination is either your Mac or any Simulator
  • Run the test action (⌘+U)

TestChat Demo Application

SocketRocket includes a demo app, TestChat. It will "chat" with a listening websocket on port 9900.

TestChat Server

The sever takes a message and broadcasts it to all other connected clients.

It requires some dependencies though to run. We also want to reuse the virtualenv we made when we ran the tests. If you haven't run the tests yet, go into the SocketRocket root directory and type:

make test

This will set up your virtualenv.

Now, in your terminal:

source .env/bin/activate
pip install git+https://github.com/tornadoweb/tornado.git

In the same terminal session, start the chatroom server:

python TestChatServer/py/chatroom.py

There's also a Go implementation (with the latest weekly) where you can:

cd TestChatServer/go
go run chatroom.go

Chatting

Now, start TestChat.app (just run the target in the Xcode project). If you had it started already you can hit the refresh button to reconnect. It should say "Connected!" on top.

To talk with the app, open up your browser to http://localhost:9000 and start chatting.

WebSocket Server Implementation Recommendations

SocketRocket has been used with the following libraries:

The Tornado one is dirt simple and works like a charm. (IPython notebook uses it too). It's much easier to configure handlers and routes than in Autobahn/twisted.

Contributing

We’re glad you’re interested in SocketRocket, and we’d love to see where you take it. Please read our contributing guidelines prior to submitting a Pull Request.

socketrocket's People

Contributors

aaronvegh avatar alanf avatar anulman avatar charlesmchen avatar dfed avatar dnkoutso avatar erikprice avatar fjolnir avatar hamchapman avatar j0sh avatar jakewharton avatar jakobsa avatar james-howard avatar jleandroperez avatar jmkk avatar kwigginton avatar kyleve avatar lukeredpath avatar m4rr avatar martinmroz avatar michaelkirk avatar mikelikespie avatar mk avatar msch avatar natan avatar nlutsenko avatar pizthewiz avatar readmecritic avatar richardjrossiii avatar scramjet 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  avatar

socketrocket's Issues

Can't connect to socket.io server

I have a socket.io server (v0.8.7) running on my machine on port 3000. I am using the TestChat project and just switched the port in the project to 3000.

On my node server, I see the connection coming in, but all it says is:

debug - destroying non-socket.io upgrade

I disabled 'destroy upgrade' in the socket.io configuration, but then I don't see anything at all.

Origin header is wrong - uses ws:// schema

Hi,

the 'Origin' header is currently based on the ws:// schema, which is wrong;
https://github.com/square/SocketRocket/blob/master/SocketRocket/SRWebSocket.m#L471

It needs to be http based; It may not directly result in an error as most server implementations have cross-origin on by default, so a 'wrong' header is not a stopper - but... IF the server is configured on certain restrictions... this becomes a problem;

See here (a java client library), which did the same fix recently (+ they corrected the actual header name):
https://github.com/sonatype/async-http-client/commit/a593230069b90d1ea80d2f39b7588df1eb960b01

I did a quick fix on my fork:
matzew@b94f627

Remove assert from send

My program just crashed because the websocket was unexpectedly closed. This is a debug build, but it seems like (as a consumer of your library) I'd rather have the delegate called with an error message, under debug and release mode.

Will provide pull request if you will accept it and tell me what error handling you want instead.

Failed to connect when on 3G/LTE

I receive this error when trying to use SocketRocket to connect with 3G/LTE on iPhone5. Is it not possible to use SocketRocket on 3G/LTE? Works no problem with WiFi.

Error:
Websocket Failed With Error Error Domain=org.lolrus.SocketRocket Code=2132 "received bad response code from server 404" UserInfo=0x2086ef60 {NSLocalizedDescription=received bad response code from server 404}

Warning in Xcode 4.4 DP3

I'm getting this warning on Xcode 4.4 DP3.

warning

Any reason not to remove __attribute__((NSObject))?

Make Test failed

Hi Mike,

I am trying to run SocketRocket but tests are failing.

command: make test
Error as follows:

** BUILD FAILED **

The following build commands failed:
PhaseScriptExecution "Run Script" build/SocketRocket.build/Debug-iphonesimulator/SRWebSocketTests.build/Script-F6BDA800145900D200FE3253.sh
(1 failure)
./TestSupport/run_test.sh: line 23: kill: (16474) - No such process
make: *** [test_all] Error 1

Thanks,
Sahil

crash when socket closes in background due to network disconnect

When the App is running in background, I've seen a couple of crashes when SRWebSocket closes due to network failure.

Thread 19 Crashed:
0 CoreFoundation 0x349d2202 CFEqual + 42
1 CoreFoundation 0x34a42db9 __CFBagStandardEquateKeys + 37
2 CoreFoundation 0x349d4b64 CFBasicHashRemoveValue + 1608
3 CoreFoundation 0x34a00551 CFRunLoopRemoveSource + 341
4 CFNetwork 0x30067a95 _CFTypeUnscheduleFromRunLoop + 285
5 CoreFoundation 0x349d774d CFArrayApplyFunction + 177
6 CFNetwork 0x30067963 Schedulables::unschedule(_CFRunLoop, _CFString const) + 39
7 CFNetwork 0x30068375 SocketStream::close(void const*) + 57
8 CFNetwork 0x300fa29b CoreStreamBase::_streamInterface_Close() + 47
9 CoreFoundation 0x349e595f _CFStreamClose + 55
10 UCA Mobile for iPad 0x000fa88d -SRWebSocket _pumpWriting
11 UCA Mobile for iPad 0x000f8eb7 __30-[SRWebSocket _failWithError:]_block_invoke_0 (UCCWebSocket.m:697)
12 libdispatch.dylib 0x3133911f _dispatch_call_block_and_release + 11
13 libdispatch.dylib 0x3133cecf _dispatch_queue_drain$VARIANT$mp + 143
14 libdispatch.dylib 0x3133cdc1 _dispatch_queue_invoke$VARIANT$mp + 41
15 libdispatch.dylib 0x3133d91d _dispatch_root_queue_drain + 185
16 libdispatch.dylib 0x3133dac1 _dispatch_worker_thread2 + 85
17 libsystem_c.dylib 0x31482a11 _pthread_wqthread + 361

received bad response code from server 400

Hey, I hope I am not making myself look too silly, but I get this error when trying to connect to : "ws://echo.websocket.org"

As referenced here:

http://www.websocket.org/echo.html

I am using the testChat example that comes with the tar ball download. And I get the error:

2012-08-06 11:31:24.200 TestChat[6437:707] :( Websocket Failed With Error Error Domain=org.lolrus.SocketRocket Code=2132 "received bad response code from server 400" UserInfo=0x1d9000 {NSLocalizedDescription=received bad response code from server 400}

This is probably my problem and not your's, and I am sorry to post this as an issue but I couldn't find any other way to get some help.

I did some googling, the only explanation i could find was that the version of web sockets that the website is using is different to that of SocketRocket, and the handshake fails. Has anyone else discovered this?

Any help would be great thanks.

--- EDIT---

It seems that it works perfectly with the test server over port 9000, but for some reason when I send the packet to connect it changes the header values of the handshake from Connection : Upgrade to Connection : Keep Alive

Implicit conversion of Objective-C pointer type

Just dropped the latest SocketRocket into my iPhone project... and it is no longer compiling...

SRWebSocket.m:47:25: Implicit conversion of Objective-C pointer type 'dispatch_queue_t' (aka 'NSObject<OS_dispatch_queue> *') to C pointer type 'void *' requires a bridged cast

SRWebSocket.m:373:5: Implicit conversion of Objective-C pointer type 'dispatch_queue_t' (aka 'NSObject<OS_dispatch_queue> *') to C pointer type 'void *' requires a bridged cast

When I try the 'fixes' that xcode recommends, it makes it worse...

Any ideas?

has anyone encountered NSPOSIXErrorDomain code=61?

I was using SocketRocket for a while and it did work. But now (suddenly) i keep getting this error.
I didn't change anything in the way i was connecting earlier.

Error Domain=NSPOSIXErrorDomain Code=61 "The operation couldn’t be completed. Connection refused" UserInfo=0x6b9cfb0 {}

I googled around but no luck. does anybody have an idea of why this error should happen?

Re-connecting a disconnected socket

In my library, I have a connection object that wraps an SRWebSocket object.

When my app loses network activity and causes a disconnection, this bubbles up using delegation and I encourage people to use Reachability at this stage to check for network availability and if necessary, wait until it becomes available before reconnecting.

What I'm finding though, is that if the web socket disconnects due to a network error (to test, I'm simply pulling out my ethernet cable), I'm unable to re-use it. Calling open on it again doesn't appear to do anything. What I end up doing is creating a brand new socket instead.

Is this expected behaviour?

Reconnect after websocket webSocket:didFailWithError:

Hi I'm having this problem:

I've already read the closed issue regarding disconnection here but I'm still having problems.

if connection get lost with webSocket:didFailWithError: (saying by putting down teh websocket server)
and i create a new SRWebSocket and try to reconnect it hangs up here:

   [_outputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
   [_inputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];


   // of this method
   - (void)_connectToHost:(NSString *)host port:(NSInteger)port;

am i doing something wrong ? my code is very simple it just on webSocket:didFailWithError: realloc a new SRWebSocket and open it after a delay

Write Queue

It would be pretty nice to have a write queue whilst the socket is waiting to be open rather than throwing an exception

didConnect: message sent to deallocated instance

Hi,

I've implemented your SRWebSocket in a IOS 5 application. I fixed a problem I had:

in didConnect (SRWebSocket.m):
2012-02-15 22:33:09.361 SC[11526:707] *** -[NSURLRequest release]: message sent to deallocated instance 0x157c30

just at

CFHTTPMessageRef request = CFHTTPMessageCreateRequest(NULL, CFSTR("GET"), (__bridge CFURLRef)_url, kCFHTTPVersion1_1);

This is my initialization code:

NSURLRequest *request = [[NSURLRequest requestWithURL:[NSURL URLWithString:@"ws://dedi.adiict.be:99999/echo"]] retain];
_webSocket = [[SRWebSocket alloc] initWithURLRequest:request];
_webSocket.delegate = self;
[_webSocket open];

See the 'retain' added when initializing the request; without it I get that error stated above. When added, everything runs smoothly...

I also noticed that

[_webSocket closeWithCode:-1 reason:@"Ok"];

doesn't seems to do anything (well I never get the delegate method called after that - nor does the 'close' method).

And when running the memory leak analyzer tool from XCode I see a bunch of potential leaks.I'll try to do some profiling to see if there really are leaks. I'm feeling like a n00b when I see some of your code...

Keep up the good work !!

Use of undeclared identifier '__bridge'

Hi, Mike,
I added the -ObjC to other linker flag, but still got 11 errors "Use of undeclared identifier '__bridge'" when trying to compile in Xcode, any idea? Thanks

YYF

Installation

Hi,

I tried now several hours to install this library in my existing iOS project but I can't get it working.
Can you please add a detailed installation instruction to the readme?

thx in advance

Runtime error

These lines of code throw a runtime exception that I just can't figure out how to solve:

static NSString* const serverUrl = @"72.249.144.156:8000";
[NSString stringWithFormat:@"http://%@", serverUrl];
[RKClient clientWithBaseURL:url];

2012-04-13 19:38:56.317 FireChat[4877:707] -[NSURL queryParameters]: unrecognized selector sent to instance 0x679cd0
2012-04-13 19:38:56.319 FireChat[4877:707] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSURL queryParameters]: unrecognized selector sent to instance 0x679cd0'
*** First throw call stack:
(0x358e688f 0x3125f259 0x358e9a9b 0x358e8915 0x35843650 0xacd15 0xacbf7 0xacb7f 0x994ad 0x990e5 0x9740d 0x95eab 0x30422e33 0x30447629 0x3040bd7d 0x304ce4dd 0x3041455d 0x30414579 0x3041440b 0x304143e7 0x30422015 0x3041b985 0x303e9c6b 0x303e970f 0x303e90e3 0x355bc22b 0x358ba523 0x358ba4c5 0x358b9313 0x3583c4a5 0x3583c36d 0x3041aa13 0x30417e7d 0x953f3 0x95398)
terminate called throwing an exception(lldb)

make test fail

On Mac OS X 10.6.8 with Xcode 4.2 build 4C177, build test failed.
(dunno if this is enough to go on - thanks for any help!)
-- Also failed on Mac OS X 10.7.3 with 4.2 build 4D199

See https://gist.github.com/1820894 for console output.

OS X loading troubles

If i add SocketRocket as a subproject to my project as described in documentation
it work fine under IDE.

But when i try to run builded app from finder it crashes with error (see log below), although SocketRocket framework lies in the same folder as a test project. How to fix that issue? Any ideas?

OS Version: Mac OS X 10.8.2 (12C60)
Report Version: 10

Crashed Thread: 0

Exception Type: EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000002, 0x0000000000000000

Application Specific Information:
dyld: launch, loading dependent libraries

Dyld Error Message:
Library not loaded: @executable_path/../Frameworks/SocketRocket.framework/Versions/A/SocketRocket
Referenced from: /Users/USER/Library/Developer/Xcode/DerivedData/testProject-hexkuefsehfplwfkcjvfvfjcchnj/Build/Products/Release/testProject.app/Contents/MacOS/testProject
Reason: image not found

Binary Images:
0x10d89e000 - 0x10d8a8ff7 +com.testProject (1.0 - 1) /Users/USER/Library/Developer/Xcode/DerivedData/testProject-hexkuefsehfplwfkcjvfvfjcchnj/Build/Products/Release/testProject.app/Contents/MacOS/testProject
0x7fff6d49e000 - 0x7fff6d4d293f dyld (210.2.3) /usr/lib/dyld

Duplicate Handshakes sent (sometimes!)

Sometimes SocketRocket sends two handshakes. I'm not sure of the reason yet but the first one is invalid, only the second one has a key that is accepted. The method to create headers is called twice according to my log message.

This is an intermittent problem which only happens every 1/10-1/20 times. Quite difficult to reproduce. I'll see if I can provide more info.

The function being called twice is

-(void)didConnect

Headers sent to server:

GET / HTTP/1.1

Host: localhost:8001

Origin: http://localhost:8001/

Sec-WebSocket-Key: KO3jnDW54UHeLHiAscOF2Q==

Upgrade: websocket

Connection: Upgrade

Sec-WebSocket-Version: 13



GET / HTTP/1.1

Host: localhost:8001

Origin: http://localhost:8001/

Sec-WebSocket-Key: 4L5fa8w2NqxQeLKs4Y9JZQ==

Upgrade: websocket

Connection: Upgrade

Sec-WebSocket-Version: 13

SocketRocket over HTTPS

Hey,

I'm trying to use SocketRocket over HTTPS and I receive an error at [websocket open]:

WebSocket did fail: Error Domain=org.lolrus.SocketRocket Code=2132 "received bad response code from server 400" UserInfo=0x849ed70 {NSLocalizedDescription=received bad response code from server 400}

SocketRocket works great when I try to use it with my local development machine which runs over plain http.
Are there any kind of special settings I have to use for HTTPS ?

Kind regards & thanks for the great library,
Raphael

Segfault on OS X

SocketRocket seems to segfault on OS X 10.6.8: travis-ci/travis-watcher-macosx#3.

I'm not quite sure if this is SocketRocket or libPusher or my app crashing, but since it's crashing in -[SRWebSocket didConnect], I'm guessing it's SocketRocket.

Does SocketRocket work on Snow Leopard?

The crash report can be found in the issue mentioned above.

Consistent 503 error when on Cellular network?

My app works great using SocketRocket within the Pusher Framework for Mac.

However, whenever I'm on my Verizon cellular modem, I receive this error (the log is of my own design but the error message comes from - (void)_HTTPHeadersDidFinish; in SRWebSocket

2012-05-13 18:05:23.040 LogMonitor[2704:503] pusher failed to connect Error Domain=org.lolrus.SocketRocket Code=2132 "received bad response code from server 503" UserInfo=0x10181f180 {NSLocalizedDescription=received bad response code from server 503}

Obviously this could be Socket Rocket, it could be Pusher, it could be Verizon, it could be my network, etc. I'm just hoping that you might have some further insight? Thanks.

Added Podspec for SocketRocket

I'm currently experimenting with swapping out ZTWebSocket for SocketRocket as the backend for my libPusher library (working pretty good so far).

Because I use CocoaPods to manage my project dependencies, I've created and pushed a podspec for SocketRocket.

Because you have no tagged versions, I've gone with 0.1 for now. If you start tagging releases in the future, the spec can be updated.

The reason I'm opening this issue is that you may want to consider including a copy of the podspec in the root of your repository; this lets CocoaPods users point to your Github repository and fetch the latest HEAD using CocoaPods.

Thanks a lot!

Using a not-connected connection hangs

Doing:

[_websocket open];
[_websocket send:(@"meh")];

prevents SocketRocket from fully opening the connection. I suppose the socket state is getting corrupted by sending before the connection is ready. It's unintuitive and I just lost 2 hours trying to figure out why my socket was not opening.

Maybe all socket operations except for open should block until webSocketdidOpen gets called?

hung websocket after websocket server restart

I find that if I restart the websocket server process, the socket rocket client does not detect the loss of websocket connection i.e. I do not get a delegate call back on either didFaileWithError or didCloseWIthCode.

I am using faye (https://github.com/faye/faye-websocket-node) on nodejs as the server and using socket rocket on ios 5.1 as client and I have implement faye client protocol on top of socket rocket. I find that other clients (faye javascript) is able to detect the server restart fine.

Basically, the websocket is hung. Trying to send message has no effect. Any help would be greatly appreciated.

allocation problems on single core hardware (<=iPhone4)

Hi there,

after checking out the latest version of socket rocket to get rid of some memory leaks, we're experiencing allocation problems on older hardware (<= iPhone 4). As we see it, this might be related to this hardware having only a single core, how weird that would be....

We're currently trying to get to a more systematic approach to see why this error comes up. Does anybody maybe have had similar issues? It seems that the malloc_error_break symbolic breakpoint doesn't work so far, but this might be another glitch in Xcode. So far we were unable to reduce the problem to a single line of code.

http://dl.dropbox.com/u/13869889/socketRocket.png

Data2Go(9780,0x4432000) malloc: *** mmap(size=43593728) failed (error code=12)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug

I know this is not much, but maybe someone already went through this trouble and may be able where the problem is on our end.

Thanks for your time in advance

Compiling for OS X, headers not available

SocketRocket doesn't appear to be OS X compatible at the moment, two of the headers it's using:

#import <unicode/utf8.h>
#import <endian.h>

Look like they're only available in the iOS SDK, I searched through my system/OSX SDK headers for a couple of the macros from those two headers and only got iPhone SDK results.

Error Domain=SRWebSocketErrorDomain Code=2133 "Invalid Sec-WebSocket-Accept response"

The bug that i'm experiencing is very frustrating and help will be very much appreciated.
The deal is this: when using iPhone simulator, request headers (from the server log) are these:
{"host":"hangies.oriben.jit.su:80",
"connection":"Upgrade",
"sec-websocket-version":"13",
"origin":"http://hangies.oriben.jit.su:80/",
"upgrade":"websocket",
"sec-websocket-key":"msASkvBQxS1TvoyPrxF+iw==",
"sec-websocket-protocol":"hangies"}

all is well and connection is established.
BUT! when using a real iphone device:
{ host: 'hangies.oriben.jit.su',
'sec-websocket-key': '42RVDx1k7NUTiQre15hXQw==',
'sec-websocket-version': '13',
origin: 'http://hangies.oriben.jit.su:80/',
'sec-websocket-protocol': 'hangies',
accept: '/',
'accept-charset': '*',
via: 'HTTP/1.1 MSP-RH',
'x-forwarded-for': '2.55.118.50',
'x-forwarded-port': '30618',
'x-forwarded-proto': 'http',
connection: 'keep-alive' }

as you can see, upgrade header is missing and connection header is 'keep-alive' instead of 'Upgrade'. this is a "regular" http request and it is being treated like such by my server, which ends up in the websocket failing to connect.

i tried setting the headers manually, like so:

NSMutableURLRequest *pushServerRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:hangiesSource]];
[pushServerRequest setValue:@"websocket" forHTTPHeaderField:@"upgrade"];
[pushServerRequest setValue:@"Upgrade" forHTTPHeaderField:@"connection"];
_socketClient = [[SRWebSocket alloc] initWithURLRequest:pushServerRequest protocols:@[@"hangies"]];

that didn't help at all. still, "connection":"keep-alive".
does anybody have an idea?

Error code 502 when connected to pusher with encrypted = NO (schema 'ws')

Failed to connect to pusher, error: Error Domain=org.lolrus.SocketRocket Code=2132 "received bad response code from server 502" UserInfo=0xf0a1930 {NSLocalizedDescription=received bad response code from server 502}

When connected using this URL ws://ws.pusherapp.com/app/ (encrypted = NO), libpusher raised the above exception.

The error goes away after switching to schema 'wss' (encrypted = YES).
wss://ws.pusherapp.com/app/

What would be the cause for 502? With encrypted = YES, what are pros and cons?

SocketRocket does not expose the binaryType attribute

The 'binaryType' attribute is missing in SocketRocket;

In the "browser world" it is set to "blob" or "arraybuffer", based on the actual binary type (since there are two different binary objects/classes: Blob or ArrayBuffer, see:

http://dev.w3.org/html5/websockets/#dom-websocket-binarytype

Not sure if this REALLY makes sense in ObjC land, since I'd expect the binaryType is "always" NSData/NSMutableData..

Perhaps it does not hurt to at least set it to something like "nsdata" .. to be somewhat compatible w/ the W3C JavaScript API

Socket Disconnect on Application Pause

As far as I can tell this seems to be a framework issue, but I may just be misunderstanding iOS:

Essentially the issue is that either the framework, or the OS, will close the socket connections on application pause (turning the screen on and off, for example), but then the framework will not correctly report that the socket is closed. When the applicationDidBecomeActive handler fires, the .readyState of the app is SR_CLOSING. In this state the only option is to create a new socket and reconnect, because you cannot close it and you cannot open it (calling [socket close] or [socket open] will crash).

So I'm wondering if this is the intended behavior, and if setting socket=nil will leak memory? I am also a bit confused because when I wrote my own NSStream socket code before, the connections would stay open after you turned the iPad screen on/off, there was a possibility that the OS may close the connection at some point, but that seems to not be the case here.

Alex

EXC_BAD_ACCESS in didConnect under iOS6

I am doing this code in the init of my UIView (Cocoa Touch) :

_webSocket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"ws://10.0.1.8:9000"]]];
_webSocket.delegate = self;
[_webSocket open];

I have a Tornado ws server running on 10.0.1.8:9000.
As soon as the UIView get initialized I have EXC_BAD_ACCESS coming from : didConnect in SRWebSocket class :

CFHTTPMessageRef request = CFHTTPMessageCreateRequest(NULL, CFSTR("GET"), (__bridge CFURLRef)_url, kCFHTTPVersion1_1);

Screen Shot 2012-12-23 at 8 28 35 PM

I am using iOS6 and I have added all the required libs listed in the readme.

Anything I am doing wrong ?

Thanks

How to set timeout for initial connection?

I tried to initialize the SRWebSocket using a NSURLRequest with a timeout of 10.0 but it doesn't seem to do anything.
Is there anyway to change the default timeout? Currently it's over a minute.

Please add semantic version tags.

We’ve recently added SocketRocket 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, SocketRocket doesn't have any version tags. We’ve added the current HEAD as version 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

callback not being dispatched

i am using socketrocket as the base for a socket.io client (kayleg's project) and i noticed that my app gets frozen in the middle with the last line in the log being: received msg: 6:::2+[{"code":200,"data":{"objects":[],"meta":{"total_count":0,"offset":0,"limit":20}}}]
what happens is that socketrocket is not launching the callback block that is supposed to call the delegate method.
the thing is that it happens exactly at the same time, at the same data everytime.

i am beginning to think that maybe i have done something wrong or maybe it's a problem with my server, so i wanted to know if anyone else has encountered this issue or maybe has an idea how to fix it?

linker problems

Hi, i keep getting this error, i guess its a library i haven´t linked ye but i dont know which one.
Should i import something else?

Undefined symbols for architecture i386:
"_EndianU16_BtoN", referenced from:
___36-[SRWebSocket closeWithCode:reason:]_block_invoke_0 in SRWebSocket.o
-[SRWebSocket handleCloseWithData:] in SRWebSocket.o
___block_global_3 in SRWebSocket.o
-[SRWebSocket _sendFrameWithOpcode:data:] in SRWebSocket.o

Data not received when not in default runloop mode

This is in relation to this issue reported to the libPusher Issue tracker.

From what I can tell, the issue lies in two places.

Firstly, the input/output streams for the socket are scheduled in NSDefaultRunLoopModes. This means when entering NSEventTrackingRunLoopMode, data will not be received until the runloop returns to the default mode.

See:
https://github.com/square/SocketRocket/blob/master/SocketRocket/SRWebSocket.m#L517

It seems like running this in NSRunLoopCommonModes might do the trick? I haven't tested this. I'm just thinking aloud.

However, this appears to be only half of the problem. All callbacks from SRWebSocket to it's delegate are performed in blocks that are executed on the main dispatch queue. Will these fire whilst the main runloop is in non-default mode? I'm not sure.

I'll try and find some time to test this but I'd welcome any other input.

Auth callbacks

For WebSocket servers that require user/password, the SRWebSocket class should expose a callback for applying the (proper) credentials.

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.