Coder Social home page Coder Social logo

socket.io-client-swift's Introduction

Build Status

Socket.IO-Client-Swift

Socket.IO-client for iOS/OS X.

Example

import SocketIO

let manager = SocketManager(socketURL: URL(string: "http://localhost:8080")!, config: [.log(true), .compress])
let socket = manager.defaultSocket

socket.on(clientEvent: .connect) {data, ack in
    print("socket connected")
}

socket.on("currentAmount") {data, ack in
    guard let cur = data[0] as? Double else { return }
    
    socket.emitWithAck("canUpdate", cur).timingOut(after: 0) {data in
        if data.first as? String ?? "passed" == SocketAckValue.noAck {
            // Handle ack timeout 
        }

        socket.emit("update", ["amount": cur + 2.50])
    }

    ack.with("Got your currentAmount", "dude")
}

socket.connect()

Features

  • Supports socket.io 2.0+/3.0+.
  • Supports Binary
  • Supports Polling and WebSockets
  • Supports TLS/SSL

FAQS

Checkout the FAQs for commonly asked questions.

Checkout the 12to13 guide for migrating to v13+ from v12 below.

Checkout the 15to16 guide for migrating to v16+ from v15.

Installation

Requires Swift 4/5 and Xcode 10.x

Swift Package Manager

Add the project as a dependency to your Package.swift:

// swift-tools-version:4.2

import PackageDescription

let package = Package(
    name: "socket.io-test",
    products: [
        .executable(name: "socket.io-test", targets: ["YourTargetName"])
    ],
    dependencies: [
        .package(url: "https://github.com/socketio/socket.io-client-swift", .upToNextMinor(from: "15.0.0"))
    ],
    targets: [
        .target(name: "YourTargetName", dependencies: ["SocketIO"], path: "./Path/To/Your/Sources")
    ]
)

Then import import SocketIO.

Carthage

Add this line to your Cartfile:

github "socketio/socket.io-client-swift" ~> 15.2.0

Run carthage update --platform ios,macosx.

Add the Starscream and SocketIO frameworks to your projects and follow the usual Carthage process.

CocoaPods 1.0.0 or later

Create Podfile and add pod 'Socket.IO-Client-Swift':

use_frameworks!

target 'YourApp' do
    pod 'Socket.IO-Client-Swift', '~> 15.2.0'
end

Install pods:

$ pod install

Import the module:

Swift:

import SocketIO

Objective-C:

@import SocketIO;

Detailed Example

A more detailed example can be found here

An example using the Swift Package Manager can be found here

License

MIT

socket.io-client-swift's People

Contributors

alevinru avatar aputinski avatar atlcto avatar banjun avatar bingfengzhu avatar callumoz avatar cfkevinref avatar craigkj312 avatar davbeck avatar dickverbunt avatar drekka avatar hankbao avatar headlessme avatar hfossli avatar kevinmartin avatar marinh avatar mephi1984 avatar musicabbage avatar nachosoto avatar naderio avatar nuclearace avatar onesman7 avatar pdupris avatar petergam avatar philipengberg avatar salpieiev avatar stevethomp avatar tbaranes avatar vonox7 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

socket.io-client-swift's Issues

Socket gets closed in background mode

Hi,
Thank you for this great lib. I am trying to receive socket.io notification while my app is in background. However, it seems that the socket.io client is suspended till the application comes back to foreground. I have tried enabling pretty much all background modes in plist and Application Capabilities Background modes. None of this works.
App goes in background and I no longer get messages till the app comes to foreground.

Any help with this would be appreciated.
Thank you

Doesn't immediately close

There seems to be a delay in closing the socket. After i call socket.close(), the socket is still open for a while and finally after a few minutes I can see that it disconnected on my server.

Engine crashes when parsing message.

when engine gets empty message with type 3, it crashes with BAD_ACCESS at socketEngine.swift line 466 after removing message type.

related code:
// Remove message type
message.removeAtIndex(message.startIndex)
dispatch_async(self.client.handleQueue) {[weak self] in
self?.client.parseSocketMessage(message)
return
}

as long as you add a message.length check to the message after you remove the message type it will not crash.

Performance issues!?

Hi there!
First of all tanks for a great framework that is Easy to setup and get started.
We recently used this framework in a lab to learn socket IO. A multiplayer version of the classic game Pong.
This exposes possible weakness of this framework.
After the two players has connected and started the game the server will emit the current "state" of the game 30 times per second.
This seems to be problematic since the socket seems to be blocking the main thread (ui thread).
The result is that the game stutters.
All form of network communication should be done on a background thread not blocking the ui.
Have you done any stress tests?

I cannot send complex json object

I tried to run this:

self.socket.emit("message","{"content":[[null,"meidika","test",null,3,1429631885,10776,0,"0161809001429095521_meidika_cropped.png",0,[],0,0,"",0,3,1429631640,[],[],0,0,1429631885,1]]}")

no error, but the data didn't accepted by server (node js) neither.

the same code works fine on browser (using javascript version, same as server). if I am trying to send that data using json, like the example, say

let myJSON = [
"name": "bob"
]

socket.emit("jsonTest", myJSON)

(quoted from http://socket.io/blog/socket-io-on-ios/#more-674), it produces error because the data is too complex to be interpreted by the library or by swift.

Please help me.. I have been finding for this problem for hours without success..
thank you, and sorry for my bad english

Swift 2

Swift 2 broke a lot of things.

Unexpected behavior of socket connection

Good day. I was working with the library all day long and unfortunately facing a lot of strange behavior. A socket connects pretty fast but then it looks like it often falls down (?) to long polling and cannot receive any message from a server. When I close a socket it can suddenly continue to reconnect repeatedly.
I've got a browser socket client running at the same time on the same mac and it receives messages just in time while the iOS client keeps silence (between reconnect attempts).

Attaching a log to show a regular case (I sent a lot of testing messages through the server before calling [socket closeWithFast:YES] method but no luck):

2015-03-26 19:29:26.344
parsePollingMessage: 2:40
Should do event: "connect" with data: "nil"
Sending ws: probe as type: 2
Sending poll: as type: 6
2015-03-26 19:29:26.523

/*
Calling:
[socket on:@"connect" callback:^(NSArray *data, void (^ack)(NSArray *)) {
[socket emitObjc:@"join room" withItems:@[@"/threads/drom-static/parom"]];
}];
*/

Sending poll: 2["join room",["/threads/drom-static/parom"]] as type: 4
2015-03-26 19:29:26.546
parsePollingMessage: 1:6
Sending ws: as type: 5
parsePollingMessage: {"code":3,"message":"Bad request"}
Should do event: "reconnect" with data: "Optional([Error parsing XHR message])"
Should do event: "reconnectAttempt" with data: "Optional([-1])"
Sending ws: probe as type: 2
Sending poll: as type: 6
Should do event: "reconnect" with data: "Optional([Socket Disconnect])"
Should do event: "reconnectAttempt" with data: "Optional([-2])"
parsePollingMessage: 2:40
Should do event: "connect" with data: "nil"
Sending ws: as type: 5
Sending ws: probe as type: 2

/*
Calling:
[socket on:@"connect" callback:^(NSArray *data, void (^ack)(NSArray *)) {
[socket emitObjc:@"join room" withItems:@[@"/threads/drom-static/parom"]];
}];
*/

2015-03-26 19:29:27.041
Sending ws: as type: 2
Sending ws: as type: 2
Sending ws: as type: 2
Sending ws: as type: 2

/*
Calling:
[socket closeWithFast:YES];
*/

Should do event: "disconnect" with data: "Optional([Fast Disconnect])"
2015-03-26 19:30:26.389
Should do event: "reconnectAttempt" with data: "Optional([-1])"
Warning! This socket was previously closed. This might be dangerous!
Should do event: "reconnectAttempt" with data: "Optional([-2])"
2015-03-26 19:30:26.729
parsePollingMessage: 2:40
Should do event: "connect" with data: "nil"
2015-03-26 19:30:26.766

/*
Calling:
[socket on:@"connect" callback:^(NSArray *data, void (^ack)(NSArray *)) {
[socket emitObjc:@"join room" withItems:@[@"/threads/drom-static/parom"]];
}];
*/

Sending poll: 2["join room",["/threads/drom-static/parom"]] as type: 4
Sending ws: probe as type: 2
parsePollingMessage: 2:40
Should do event: "connect" with data: "nil"
Sending ws: probe as type: 2
2015-03-26
Sending poll: as type: 6
Sending poll: as type: 6
pSarsePolelningMedssage: 1:i6
ng ws: as type: 5
Sending ws: 2["join room",["/threads/drom-static/parom"]] as type: 4

… repeated indefinitely

Initial connection timeout

There appears to be no timeout specifiable for the initial connection:
[self.socket connectWithParams:@{@"token":token, @"mac":mac}];

Every request after that (emitWithAck) takes a timeout which is great.
The initial request takes a reconnectWait option, but that only applies after the first connection fails, and the first connection's timeout appears to be 75 seconds, and it's uncustomizable.

Am I overlooking something?

Suggestion: let some more people know about this project

I have been using this lib in a beta version of our product. I know it's still very early days, but based on my experience, compared to other alternatives I feel this is by far the best option out there (for socket.io 1.0+ and iOS 7 and up obviously).

@nuclearace you know @rauchg, or at least have an online rapport with him. I see that the Socket.IO FAQ only mentions SIOSocket, and I feel like this project should definitely be up there as options for iOS.

Thoughts?

SecRandomCopyBytes issue when switching Swift 1.2

Figured its an obvious fix but it had me baffled until I noticed the error >.< long day lmao

Swift 1.2 uses func SecRandomCopyBytes(rnd: SecRandomRef, count: Int, bytes: UnsafeMutablePointer) -> Int32 rather than func SecRandomCopyBytes(rnd: SecRandomRef, count: UInt, bytes: UnsafeMutablePointer) -> Int32

So just change the UInt(sizeof(UInt32)) to Int(sizeof(UInt32))

Remote server connection error?

I am trying to connect a socket to my remote server with the following syntax:
let socket = SocketIOClient(socketURL: "my.server.com:port")
I have tried this with and without the port referenced and http:// added

When I call socket.connect() I receive the following errors:

SocketClient: Adding handler for event: connect
SocketClient: Adding handler for event: error
SocketClient: Adding engine
SocketEngine: Starting engine
SocketEngine: Handshaking
SocketEngine: Doing polling request
ERROR SocketClient: Error: Could not connect to the server.
SocketClient: Handling event: error with data: Optional([Could not connect to the server.])

I am 100% certain that the server is handling appropriately. I did notice all the examples given using this library are using localhost instead of a remote server connection. Something else to note is that the server is hosted by heroku. However, we have an equivalent app that is for android which connects to it just fine.

Is anyone able to explain why I am having this issue?

Connect to remote server

Hello,
For some reason, i cannot connect socket.io to a remote server.
When using localhost it worked fine, but when switching, nothing happens.

Any help?

Message Sending Failed while sending complex JSON.

In my current project I am sending some string to the socket. When the string is simple (example "Sauvik Dolui"), server is successfully receiving the string. But when I am sending a complex JSON string like

{
"placeID": "554c547a079c79dc3c71572b",
"type": 2,
"user": {
"gender": 1,
"isInvisible": false,
"lastName": "Dolui",
"firstName": "Sauvik",
"profilePicture": "https://.....r.jpg",
"dob": "1978-05-03T00:00:00.000Z",
"_id": "55475ed29ee11a140728672f",
"preferredLanguage": "en-us",
"isLoggedIn": false,
"isAlreadyBlocked": false,
"socialId": "805597032855698",
"socialType": 1,
"deviceType": 0,
"hideName": false,
"email": "[email protected]",
"statusText": "Searching for a playground nearby for playing Football.",
"visitedCount": 1
}
}

then the sending failed.

42 :-)

What is the meaning of the special value "42" in SocketIOClient.swift, and likewise "43" "45" and "46" in the same file.

The == comparison in master has changed to hasPrefix("42") in 1.2 branch.

Which could be the reason for me not receiving messages/events from the server. Should this change be merged into master?

Crashes on reconnection

Hi,

I am using Socket.IO-Client-Swift in a project written in Objective-C. I still support iOS 7.1

I encounter one crash on line 291 in SocketEngine.swift

    if self.connected {

        assert(false, "We're in a bad state, this shouldn't happen.") //crashes here
    }

Steps to reproduce:

  1. Go to first screen of the app. Open a socket connection.
  2. Lock the screen of the device for 20-30 seconds.
  3. Unlock the screen and quickly navigate away from the current view controller of the app to another view controller. This will call socket.close()
  4. In a few seconds the socket library tries to reconnect and then it goes to this "bad" state.

Do you have any ideas guys how to fix it?

Thanks in advance.

Will not connect to client when adding a namespace

Hi nuclearace,

I'm trying to implement this library for some weeks now, but facing problems when using a namespace. I tried almost everything to make it work, like different options based on our client, but it just won't connect.

Code:

let socket = SocketIOClient(socketURL: "ws-xxxx.xxxxx.net", opts: ["nsp":"chat", "log":true])

The following things I tried:

  • adding portnumber (Engine is being deinit after doing polling request)
  • adding "/chat" as namespace, gives almost the same feedback as without the slash

Scenario:

  • We use Socket.IO client version 1.2
  • Without a namespace it connects perfectly, but with a namespace it tries to do a lot of things, see the log below:
  • The declaration of the socket happens on the global scope

SocketClient: Adding handler for event: connect
SocketClient: Adding engine
SocketEngine: Starting engin
SocketEngine: Handshaking
SocketEngine: Doing polling request
SocketEngine: Got polling response
SocketEngine: Got message: 0{"sid":"xxxxxxxxxxxxxxxxxxxx","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":60000}
SocketEngine: Doing polling request
SocketEngine: Flushing probe wait
SocketEngine: Got polling response
SocketEngine: Got message: 40
SocketEngine: Doing polling request
SocketParser: Parsing 0
SocketParser: Decoded packet as: SocketPacket {type: 0; data: nil; id: nil; placeholders: nil;}
SocketClient: Joining namespace
SocketEngine: Writing poll: 0/chat:nil
SocketEngine: Sending poll: 0/chat as type: 4
SocketEngine: POSTing: 7:40/chat
SocketEngine: Writing poll: :nil
SocketEngine: Sending poll: as type: 2
SocketClient: Handling event: reconnect with data: Optional([Ping timeout])
SocketClient: Starting reconnect
SocketClient: Trying to reconnect
SocketClient: Handling event: reconnectAttempt with data: Optional([-1])

I will be very grateful if you're able to look into the matter. If you need more information, I'll respond very quickly. Thanks in advance!

recognize if socket has been connected successfully

I am new to swift and socket.io and am following your example given here. Following is the code am using to create a socket:

    let socket = SocketIOClient(socketURL: "http://52.someIP.237:8100")
    socket.connect()

But how do I recognise whether the socket is successfully connected or not? Through debugging I got to know that open method is called in SocketEngine.swift but it returns after executing the following code:

self.session.dataTaskWithRequest(reqPolling) {[weak self] data, res, err in var err2:NSError? if self == nil { return // returns here } else if err != nil || data == nil { // executes first self?.handlePollingFailed(err) return }
And in res object I get :

<NSHTTPURLResponse: 0x7fa321718790> { URL: http://52.someIP.237:8100/socket.io/?transport=polling&b64=1 } { status code: 200, headers { Connection = "keep-alive"; Date = "Thu, 14 May 2015 08:49:30 GMT"; "Transfer-Encoding" = Identity; } }

Does this mean the socket is cerated and ready? If I specify a wrong URL then also it returns on this very same point.

Please help. Thanks in advance

Public variables (Objective C support)

The following variables are not visible for the Objective C compiler. If declared as public, it works:

    var closed = false
    var connected = false
    var connecting = false
    var engine:SocketEngine?
    var nsp:String?
    var reconnects = true
    var reconnecting = false
    var reconnectWait = 10
    var secure:Bool {
        return self._secure
    }
    var sid:String?

If you could declare them as public, that would be nice.

joining multiple namespaces?

is it somehow possible to join multiple namespaces?

€dit:
at the same time i wondered (if you can join multiple) - how you can emit to the specific one then?

obj-c interface

SocketIOClient.swift L 217

public func emitObjc(event:String, withItems items:[AnyObject]) {

should be

public func emitObjc(event:String, withItems items:AnyObject) {

?

Basic Auth/Tokens

Hi,

Using this currently without auth and it's working well.

We are planning to use basic auth or JSON tokens to secure our rest API.

Is there, or are there any plans to integrate auth into this framework?

Thanks

Gareth

Error in groups

Hi! First of all thanks for making this library, i've been very happy with it. I just made a pull (commit c6d0331) and am getting "error in groups". Know something about this?

unable to fire functions in socketioclint.swift

Hi, Im trying to make an IOS app to connect to arduino via a wifly shield. I got the shield listening in 192.168.1.111:8000. Im able to connect and disconnect to the wifly board, but I'm not able to send data. On further study, i found that the code is not firing func websocketdidopen() on opening the port (same with closing).The events including socket.on("connect") do not respond after connection is created.
Please help me out.
code:

import UIKit
import Foundation
class ViewController: UIViewController {
var connectionStatus: Bool = false
let socket = SocketIOClient(socketURL: "192.168.1.111:8000", opts: nil)

@IBOutlet weak var connectButton: UIButton!
@IBOutlet weak var testButton: UIButton!
@IBOutlet weak var status: UILabel!
@IBAction func connectButton(sender: AnyObject) {
        socket.connect()

            self.status.text = "Connected"
            self.connectButton.hidden = true
            self.testButton.hidden = false

    disconnectButton.hidden = false

    socket.on("connect") {data in
        println("socket connected")

           }
}

@IBAction func sendTestMessage(sender: AnyObject) {
 socket.emit("echo")
    socket.sendPing()

    println("echo")


}

@IBOutlet weak var disconnectButton: UIButton!
@IBAction func disconnectButtonPressed(sender: AnyObject) {
    disconnectButton.hidden = true
    connectButton.hidden = false
    testButton.hidden = true
    socket.close()
    socket.on("disconnect") {data in
        if let reason = data as? String {
            println("Socket disconnected: \(reason)")
        }
    }
}

//functions




override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    testButton.hidden = true
    disconnectButton.hidden = true
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

Error message file extension type not supported

Hi,
I'm trying to implement this library to my swift project. I have a server application listening on the port 5260 and waiting for message.
When I start the app the server start the connection but immediately I got this error message : file extension type not supported : .//socket.io/?transport=polling&b64=1

Any idea?
Thx!

Importing into Objective-C, header not found?

Manually imported files into my project, made sure they were added to the target and exist in Compile Sources.

Trying to import "SocketIOClient-Swift.h" as per instructions from the link provided to Apple's documentation but it doesn't work. I've set "Define Modules" in Build Settings to be "Yes" as well.

How do I import the files into my project?

Fallback to XHR polling?

I'm not even sure if this is necessary on native mobile platforms, but is it not possible that the phone is connected to a wi-fi network which only allows HTTP traffic, and blocks WS connections? In such cases it would be nice to fallback to XHR / long polling, right?

I see these projects both have done something along those lines:
https://github.com/francoisp/socket.IO-objc
https://github.com/shuoli84/SocketIOCocoa

This project definitely has the nicest API out of all that I have seen, so I wanted to try it first and see how I go with it. I especially like the ACK's on the 1.2 branch: #10

@nuclearace please feel free to comment and say if you don't think this is needed / would help much with getting better connectivity to the server under certain conditions.

And thanks for starting a cool project.

Connect again after closing socket

When I close the socket and then connect again, my listeners are called twice. I know that in the readme it says the socket shouldn't reconnect after closing, but is there any way to fix this? Thank you!

ack parse problem

Ok, so i've got a weird issue. Don't know if it's the device or not but i'm getting a very strange outcome:

first, when i run in the simulator, the ack executes just fine. I've commented the NSLog so i can see the parsed string:

31[{"OK":"200","FAIL":"500","code":"200","message":[{"registeredContacts":[{"password":"688274158da469097c6c766277fac272","phone_number":"+31322323","created_at":null,"updated_at":null,"email":"[email protected]","id":"2","push_notification_token":"<1234>","device_id":"2323232"}]},{"groups":[{"admin_id":"2","created_at":"2015-03-16T19:22:57.747Z","updated_at":"2015-03-16T19:22:57.747Z","id":"230"}]},{"groupsMembers":[{"groupMember":{"user_name":"Test ","going_status":"going","group_id":"230","user_id":"19","user_phone_number":"+6456546599","created_at":"2015-03-16T19:22:57.759Z","updated_at":"2015-03-16T19:22:57.759Z","id":"287","external_id":"undefined","unreg_user_unique_link":null}},{"groupMember":{"user_name":"badescuga ","going_status":"going","group_id":"230","user_id":"2","user_phone_number":"+654645693","created_at":"2015-03-16T19:22:57.758Z","updated_at":"2015-03-16T19:22:57.758Z","id":"288","external_id":"1180E999-5DC6-415E-B064-D2930D471274","unreg_user_unique_link":null}}]},{"events":[{"admin_id":"2","start_date":"2015-03-16T21:21:33.846Z","end_date":"2015-03-16T21:21:33.846Z","group_id":"230","title":"Testv121","created_at":"2015-03-16T19:22:57.771Z","updated_at":"2015-03-16T19:22:57.771Z","location_id":"","id":"151","location_name":""}]},{"userId":19,"phoneNumber":"+6546453699"}]}]

when i install on the device, the ack doesn't get executed and the swift parse NSLog fires this up:

32[{"code":"200","message":[{"registeredContacts":[{"password":"53df40871f37e91cc85c7a19edc3cfc7","phone_number":"+545354353","created_at":"2015-02-21T18:52:51.743Z","updated_at":"2015-02-21T18:52:51.743Z","email":"[email protected]","id":"26","push_notification_token":"<43242 42342 43242 >","device_id":"4343434351217B291A"},{"password":"688274158da469097c6c766277fac272","phone_number":"+445454543699","created_at":null,"updated_at":null,"email":"[email protected]","id":"19","push_notification_token":null,"device_id":"F74B850D-AD5C-4042-890D-F1E3471B455D"},{"password":"688274158da469097c6c766277fac272","phone_number":"55344393","created_at":null,"updated_at":null,"email":"[email protected]","id":"2","push_notification_token":"<30f5eab5 a6cb6654 e5e367bc fe911709 159f9221 22c774f1 ffd5eee8 c9d01e72>","device_id":"424324234"}]},{"groups":[{"admin_id":"2","created_at":"2015-03-16T19:22:57.747Z","updated_at":"2015-03-16T19:22:57.747Z","id":"230"},{"admin_id":"2","created_at":"2015-03-16T20:00:58.163Z","updated_at":"2015-03-16T20:00:58.163Z","id":"231"}]},{"groupsMembers":[{"groupMember":{"user_name":"Test ","going_status":"going","group_id":"230","user_id":"19","user_phone_number":"+40724263699","created_at":"2015-03-16T19:22:57.759Z","updated_at":"2015-03-16T19:22:57.759Z","id":"287","external_id":"undefined","unreg_user_unique_link":null}},{"groupMember":{"user_name":"badescuga ","going_status":"going","group_id":"230","user_id":"2","user_phone_number":"+3424323693","created_at":"2015-03-16T19:22:57.758Z","updated_at":"2015-03-16T19:22:57.758Z","id":"288","external_id":"434234234-D2930D471274","unreg_user_unique_link":null}},{"groupMember":{"user_name":"badescuga ","going_status":"going","group_id":"231","user_id":"2","user_phone_number":"+42343263693","created_at":"2015-03-16T20:00:58.174Z","updated_at":"2015-03-16T20:00:58.174Z","id":"289","external_id":"193A3A8E-D1C1-4E5F-84A3-744495C686BE","unreg_user_unique_link":null}}]},{"events":[{"admin_id":"2","start_date":"2015-03-16T21:21:33.846Z","end_date":"2015-03-16T21:21:33.846Z","group_id":"230","title":"Testv121","created_at":"2015-03-16T19:22:57.771Z","updated_at":"2015-03-16T19:22:57.771Z","location_id":"","id":"151","location_name":""},{"admin_id":"2","start_date":"2015-03-16T21:59:21.478Z","end_date":"2015-03-16T21:59:21.478Z","group_id":"231","title":"aici e un test","created_at":"2015-03-16T20:00:58.180Z","updated_at":"2015-03-16T20:00:58.180Z","location_id":"","id":"152","location_name":""}]},{"userId":2,"phoneNumber":"+42142141241"}]}]

Note: the accounts i'm testing are different so that's why te actual text (the json being sent) is different. The device is iPhone6(iOS,8.2), if that actually matters.

Support for Rooms

First off, thanks for building a client like this it's extremely useful and much needed. So I'm building an application which deals with using SocketIO rooms and I was wondering if this is possible using this Client. Looking through the source code I noticed there was a joinNamespace function but I couldn't find a join function that handled rooms and I was wondering if one existed .

socket.on('disconnect', function(data)){} not called.

In my project first I am connecting to the main socket server. After that a new room dynamically created in server side. I receive the name of that room. I then set the socketIOClient's namespace to that one, and call joinnamespace(). When I am leaving the room, I set the namespace of socket client as '/' and call joinnamespace() again. But in server side socket.on('disconnect', function(data)){} is not called. Please advice me to leave a dynamically created namespace so that socket.on('disconnect', function(data)){} is called in server side. Thanks in advance.

Handshake (connect) with parameters

Enhancement request: It would be nice if there was a second connect() method that takes custom parameters for the handshake. That way, the client could tell the server an auth token or other data it wants the server to know upon connection.

Socket Id

Appreciating the latest changes a lot, it makes using the library a lot easier with Objective-C.
The socket id property ("sid") of the SocketIOClient object (of which we're making use in our project) seems to be null all the time. From looking at the source, it seems like it's not set anywhere anymore. Is it possible to get the socket id somehow?

"Guaranteed" callback for emit

The following is not an issue, but maybe a feature request:

Let's say in the context of a chat we want to show the user the state of the messages he sends (e.g. "sending", "received by server", "failed transmission" etc.). We're using the emitWithAck: method making use of the acknowledgement callback to determine whether the server has received the message. If so, we can change the state of the message in the UI from "sending" to "received".

In a lot of cases, this works fine. But there are situations, where the ack callback is never called (for instance due to a lossy networks that mobile devices may find themselves in from time to time). The problem is now: When and how do we know that the transmission of that specific message has failed so we can show that to the user in the UI?
As far as I have understood socket.io so far, the protocol does not provide mechanisms to cope with this situation, though not too sure. This is in contrast to let's say AFNetwork where either the success or the error callback block will always be called.

I'm assuming we would need to implement some kind of queue to keep track of the messages that we emitted and at every emit: we'd have to start a timer that after let's say 20seconds will decide whether the emit has been acknowledged and if not, we'd mark the message as "failed transmission".

Another solution could be a variant of the emitWithAck: method where the (ack) callback will be always called (guaranteed): either with the ack from the server, or (after a configurable timeout) with the timeout event. Someone has done something like this for node.js: https://www.npmjs.com/package/timeout-callback

What do you think about it in general (am I missing something here)?
Any chances your client library could provide this convenience?

Engine is being deinit

Hi,

Upon attempting to connect, using this code:

SocketIOClient * socket = [[SocketIOClient alloc] 
        initWithSocketURL:@"http://localhost:3456/" 
                  options:@{@"log":@YES}];

[socket on:@"connect" callback:^(NSArray * data, void (^ack)(NSArray *)) {
    eoLog(@"socket connected");
}];

[socket connect];

I get these log messages:

SocketClient: Adding handler for event: connect
SocketClient: Adding engine
SocketEngine: Starting engine
SocketEngine: Handshaking
SocketEngine: Doing polling request
SocketClient: Client is being deinit
SocketEngine: Engine is being deinit

So it appears SocketIOClient is trying to connect, then immediately disconnecting - socket on:@"connect" never fires.

I'm using a node server with this version of socket.io:

"socket.io": "^1.3.5",
"socket.io-client": "^1.3.5",

FWIW, I'm able to connect to the server using SIOSocket. But that's on iOS (it's not available for OSX - which is where I'm connecting now...) So I don't think anything is wrong with the server.

Any idea why this might happen?

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.