megabits / siosocket Goto Github PK
View Code? Open in Web Editor NEWRealtime iOS application framework (client) http://socket.io
License: MIT License
Realtime iOS application framework (client) http://socket.io
License: MIT License
When my app got suspended in background mode connection get lost. And when I am again putting it in foreground then reconnection takes around 1 min. That is why I want to know connection status so that I can create new connection coming back in foreground.
Is there a reason why this library isn't available for OS X? Could be great to handle iOS and OS X at the same time.
Hi
I've experienced weird error and it happen in iOS8+ only,
The error is SIOSocket intermittently didn't send the emit message to server.
Please help,
Hi,
I am testing the library on iPhone 5C (iOS 7).
I have 2 screens in the app. On the second screen I open the connection, and when navigating back I close the connection.
The problem is if I do it very fast (navigating back and forward between the screens), then I receive crash in the following line (the method close):
[self.javascriptWebView loadRequest: [NSURLRequest requestWithURL: [NSURL URLWithString: @"about:blank"]]]; //crashes here
[self.javascriptWebView reload];
self.javascriptWebView = nil;
I am not able to reproduce it on newer devices (iPhone 6 and 6+)
Thanks,
Osman
I use SIOSocket to connect with the server in Swift, there is an event to monintor the mouse movement. In order to complete it, I use an icon in iOS platform, so that the icon would move according to the coordinates sent by the browser. I have an IOS7 iPhone 5 in which it works spectacular. However, the IOS8 iPhone5s the millisecond interval seems to act weird. It seems to hang for 800 ms, then quickly tick 0-10 in 200 ms instead of evenly distributing the tick.
this is my code in ios
self.socket.on("mouse location msg", callback: { (args:[AnyObject]!) -> Void in
dispatch_async(dispatch_get_main_queue()){
var value = args.first as NSDictionary;
var data = value.valueForKey("data") as NSArray;
var m_point = CGPoint(x: data[0] as CGFloat , y: data[1] as CGFloat)
m_point = self.main.getPointLocationInView(m_point.x, _pointY: m_point.y)
self.pen.frame.origin.x = m_point.x
self.pen.frame.origin.y = m_point.y;
self.updatelogs("\(m_point.x),\(m_point.y)\n")
}
})
When I nil out my strong reference to the SIOSocket
object, I expect it to get dealloc
ed immediately (or in the next run loop). But it actually gets released much later, at times when simulating the memory warning.
Why's that?
- (void)testConnectToLocalhost {
XCTestExpectation *connectionExpectation = [self expectationWithDescription: @"should connect to localhost"];
[SIOSocket socketWithHost: @"ws://sdfsdf" response: ^(SIOSocket *socket) {
XCTAssertNotNil(socket, @"socket could not connect to localhost");
[connectionExpectation fulfill];
}];
[self waitForExpectationsWithTimeout: 10 handler: nil];
}
For any host this Socket will say that the connection is opened. Is there any reason why? Because I want to know if I can reach a specific WebSocket server, and this was the way that I was introduced to in Tests
I am developing a application of two-way communication in SocketIO between App of iPhone and server.
I would like to implement the authentication function when connecting from the application side to the chat server.
I have implemented on the server side as described below.
io.set('authorization', function (handshakeData, callback) {
var token = handshakeData.query.token;
checkAuthToken(token, callback);
});
However, I do not know where I should set the token in the app side.
var socket:SIOSocket! = nil
SIOSocket.socketWithHost("ServerUrl" , response: { (_socket: SIOSocket!) in
self.socket = _socket
println(self.socket)
self.socket.onConnect = {() in
println("connected")
}
})
To borrow your wisdom.
Hi,
I'm running v0.2.2 of SIOSocket, and I'm getting an EXC_BAD_ACCESS exception in WebThread. Here's an XCode screenshot:
I have a callback function set up so that when I receive an event called "chatMessage" I run a block of code. Something like this:
[self.socket on: @"chatMessage" callback: ^(SIOParameterArray *args) {
[self chatMessageReceived];
}];
This in calls a function which updates a badge counter on a bar button like so:
self.chatBarButton.badgeValue = [NSString stringWithFormat:@"%d", _unreadChatMessages];
Which is accomplished in the bar button code as follows:
[UIView animateWithDuration:duration animations:^{
[self updateBadgeFrame];
}];
Looking at the inspector, it seems as thought UIView is not defined? Is this because we are running in the wrong thread?
Hello there, im having some issue there if i open the explorer all of the emit methods works like a charm, but in iOS not.
Any idea why is that happening, some of code here:
Server:
io.on('connection', function(socket)
{
ClientsArray.push(new function () {
this.userid = "";
this.socketid = socket.id;
});
socket.on('disconnect', function ()
{
for (var i = 0; i < ClientsArray.length; i++)
{
if (ClientsArray[i].socketid == socket.id)
{
ClientsArray.splice(i, 1);
break;
}
}
console.log(ClientsArray);
});
socket.on('chat message', function (msg)
{
var Ms = msg;
console.log(msg);
try
{
var arr = msg.split(";-:-;");
var toSocketID;
for (var i = 0; i < ClientsArray.length; i++) {
if (ClientsArray[i].userid.toString() == arr[1]) {
toSocketID = ClientsArray[i].socketid;
break;
}
}
io.sockets.connected[toSocketID].emit('chat message', msg);
socket.emit('chat message', msg);
}
catch (err)
{
socket.emit('chat message', msg);
}
});
socket.on('id cliente', function (msg) {
try {
for (var i = 0; i < ClientsArray.length; i++) {
if (ClientsArray[i].socketid.toString() == socket.id.toString()) {
ClientsArray[i].userid = msg;
break;
}
}
socket.emit('done');
}
catch(err)
{
console.log(err);
}
});
});
Objective C:
+(ConexionSocket_)sharedModel
{
static ConexionSocket_ ConexionCompartida = nil;
if(!ConexionCompartida)
ConexionCompartida = [[ConexionSocket alloc] init];
return ConexionCompartida;
}
-(void)IniciarConexion
{
[SIOSocket socketWithHost: @"http://104.236.96.130:9000/" response: ^(SIOSocket *socket)
{
SocketS = socket;
id _c = cliente;
SocketS.onConnect = ^()
{
[_c OnSocketConnection];
};
SocketS.onDisconnect= ^()
{
[_c OnSocketDisconnect];
};
SocketS.onError = ^(NSDictionary* D)
{
};
[SocketS on:@"chat message" callback:^(SIOParameterArray *args)
{
NSArray *array = [args.firstObject componentsSeparatedByString:@";-:-;"];
Mensajes *MSJ = [[Mensajes alloc] init];
MSJ.IdEmisor = array.firstObject;
MSJ.IdReceptor = [array objectAtIndex:1];
MSJ.Mensaje = array.lastObject;
[cliente OnMensajeRecibido:MSJ];
}];
[SocketS on:@"done" callback:^(SIOParameterArray *args)
{
NSLog(@"Here");
}];
}];
}
-(void)enviarMensaje: (NSString_)mensaje MensajeTraducido: (NSString_)mensajeTraducido To:(id)to From:(id)from
{
[SocketS emit:@"chat message" args:@[[NSString stringWithFormat:@"%@;-:-;%@;-:-;%@;-:-;%@",from, to,mensaje, mensajeTraducido]]];
}
-(void)enviarmensajeConfirmacion: (id)idUsuario
{
@Try
{
NSArray *Arr = [NSArray arrayWithObjects:idUsuario, nil];
[SocketS emit:@"id cliente" args:Arr];
}
@catch (NSException *exception)
{
NSLog(@"Error %@", exception);
}
@finally
{
}
}
In objc_onConnect
and friends, capturing socket
string within the block is likely to lead to a retain cycle.
I use the following JavaScript code to over-ride the default transports
setting to only use websocket
.
var socket = io('http://localhost:8080/user-data-sync', {
transports: [ 'websocket' ]
});
Is this possible with the SIOSocket client? This is a big deal for a project that I am working on where the client and server both support WebSockets, but there are technical reasons to avoid doing the handshake over long-polling.
Does SIOSocket support acknowledgements, when receive a event then send back some data?
I have read the read me but cannot find anything about namespaces. Does SIOSocket support namespaces? If not do you consider implementing this enhancement?
accidentally made some bad json, it was a string. tried to emit it, did not emit, fails silently. i tried to emit this: (swift syntax) "{key1:\(myVal1!),key2:'\(myVal2)'}"
i suspect the problem was due to my keys not being wrapped in quotes, or my use of single quotes around myVal2, fixing both of these, it works.
The method emit is not accessible in swift because it is a variadic method.
I had a accessible socket class through a bridging header and every method was accessible except for emit.
I also tried a solution from Stack, http://stackoverflow.com/questions/24195796/how-do-you-call-an-objective-c-variadic-method-from-swift but i didn't got it to work.
A possible workaround would be a method with a NSArray as argument like this:
One day I set up a incorrect address,like
[SIOSocket socketWithHost:@"http://www.xxx.com" response:^(SIOSocket *socket) {
NSLog(@"response");
}];
and the memory keeps raising until I close the socket manually by [socket close].
Anybody meet this issue like me ?
Is there any reason why we are using a UIWebView? I think we can get better performance and better threading if we switch to Javascriptcore. https://www.infinum.co/the-capsized-eight/articles/running-javascript-in-an-ios-application-with-javascriptcore
Hi. I've cloned this project, and tried a simple test with an existing socket.io v1.2.1 server.
I've connected to the server, but can't receive any of the messages emitted by it. I tried both sending messages on the "update" event and on another custom one (which i've added a listener to in-app), but don't receive any of them. It was not receiving atleast onConnect event.
Is there anything I'm missing? Should I change anything else but the actual host?
I always got the above error. My project has heavy UI created with storyboard, and in-house library as another library project referencing by project I'm trying to build. I tried to create a new project with nothing, and then add only SIOSocket, it can build just fine.
Then I try to remove all those storyboard files, and rebuild the project. It shouts out the same error as above. Even I tried to change the storyboard's version to 7.0+. It didn't help, and the same error appears. Thus at least I can be sure that storyboard files don't involve with the error. Anyway I can't really find anything wrong with the project being built.
Any idea would be welcome.
I tried to connect to a socket.io v1.0 using SSL and it was not possible. But it was using a non-SSL connection. Could you please enable SSL? Can I help you with this?
Thanks
Does anyone experience freeze issue, it is happening on device randomly and i cannot debug it on XCode because there are no error log or something else.
Thanks,
That'd be obviously the nail in the coffin.
Hi,
I'm not sure any one here has faced the same issue. I'm working on iOS 8 and iPhone 5s. What I observe is intermittently (and repeatedly) socket emit and on to and from the server doesn't work. Sometimes the events are emitted but it doesn't reach the server. In other cases, event is sent by the server but not received by the client. It looks like I have no control over it and makes the app functionality very flaky.
Any thoughts or ideas on this issue? Thanks...
How do we handle new event when the app enter background mode?
Here under is my approach for this, but it still doesn't work
Thank you very much for your suggestion
// on app delegate
- (void)applicationDidEnterBackground:(UIApplication *)application {
[self.sharedSocket on:kMESSAGE callback:^(SIOParameterArray *args) {
NSLog(@"it does work in here too!");
}];
}
// on other controller
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
[SIOSocket socketWithHost:kHOST_URL response:^(SIOSocket *socket) {
appDelegate.sharedSocket = socket;
self.mySocket = socket;
[self.mySocket on:kMESSAGE callback:^(SIOParameterArray *args) {
NSLog(@"it works!");
}];
//other logic code
}];
If we would install SIOSocket via CocoaPods and open socket.io.js.h file then we would see this comment in the header:
/*!
But the source file in GitHub has another comment:
/*!
HI,
I'm working with SIOSocket with 1.3.6 socket.io. how do I send ack on receiving an event?
Hello, I'm facing an issue. I follwed your example WorldPin and wrote the code below. I can see connection opened on the server, but no message is actually emmited. I don't get any errors etc. I am clueless. Thanks in advance for any help.
-(void)connectSocket:(NSString *)token
{
NSString *hostURL = [NSString stringWithFormat:@"%@/%@?accessToken=%@", kPHServerBaseURL, @"socket.io", token];
DLog(@"%@", hostURL);
[SIOSocket socketWithHost:hostURL response:^(SIOSocket *socket) {
self.socket = socket;
__weak typeof(self) weakSelf = self;
self.socket.onConnect = ^() {
weakSelf.socketIsConnected = YES;
DLog(@"CONNECTED");
[weakSelf.socket emit:@"join", @{@"id": weakSelf.chatRoom.ID}, nil];
};
self.socket.onError = ^(NSDictionary *data) {
DLog(@"error: %@", data);
};
self.socket.onReconnectionAttempt = ^(NSInteger recCounter) {
DLog(@"Reconnection counter %li", (long)recCounter);
};
self.socket.onReconnectionError = ^(NSDictionary *data) {
DLog(@"reconnection error: %@", data);
};
[self.socket on:@"msg" do: ^(id data) {
DLog(@"NEW MESSAGE! \n on: msg, %@", data);
[JSQSystemSoundPlayer jsq_playMessageReceivedSound];
[weakSelf receivedMessageData:data];
[weakSelf finishReceivingMessage];
}];
[self.socket on: @"notice" do: ^(id data) {
DLog(@"NEW NOTICE!! %@", data);
}];
}];
}
- (void)didPressSendButton:(UIButton *)button withMessageText:(NSString *)text sender:(NSString *)sender date:(NSDate *)date
{
[JSQSystemSoundPlayer jsq_playMessageSentSound];
AMChatMessage *message = [[AMChatMessage alloc] initWithText:text sender:sender date:date];
if(self.socketIsConnected) {
[self.messages addObject:message];
[self.socket emit:@"msg", @{@"body": text, @"room": self.chatRoomModel.ID}, nil];
DLog(@"MESSAGE SENT");
[self finishSendingMessage];
} else {
DLog(@"NOT CONNECTED");
}
}
the data send from server is
{"name: "中"}
but client got wrong string.
[socket on:@"event" do:^(id data) {
data[@"name"] //is - , not 中
}];
There is something wrong when parsing data, please fix it.
Hi, we have an issue, we cannot send a message if it contain a quote [ ' ], the nodeJS server just does not receive the message.
Other messages works fine, but if iOS client send a quote in a string it does not work.
Any clues? or we have done something wrong (we use the exact same methods for both case in iOS)
Thanks for your work!
say you have a connected socket named socket
socket?.on("a-b-c", callback: { (msg) -> Void in
// I will never receive anything on this channel
})
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.
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 am wondering how to do that since I started to work with this lib.
Did somebody think about it?
In theory it would be perfect to call the 'calback' function from default socket.io implementation rather than use 2 emit calls (client->server(request) and server->client(response))
Is there support to add additional hanshake data?
I have the latest version from cocoapods (with socket.io-1.2.1.js) and there are no special characters accepted in UTF-8 (e.g. Ł changes to A, emoticons to random numbers etc.).
I did test the socket using web client, it's just doesn't work on my mobile.
I discovered it actually happened when I migrated from version 0.0.3 to 0.1 - when I use 0.1 and above the encoding is bad.
In 0.0.3 UTF-8 works but I would prefer to use newest one, because there was one pull that allows specifying transportation (helped me to make it work on Heroku with multiple dynos). Btw it would be nice to merge it.
P.S. This is the way I do it in version 0.0.3 which accepts NSString only and I need to send a dictionary:
{
....
NSDictionary *message = @{@"body": text, @"room": self.chatRoomModel.ID};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:message options:0 error:&error];
if (jsonData) {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[self.socket emit:@"msg", jsonString, nil];
}
}
It would be good to list in the README which versions of Socket.io this supports since there's slight protocol differences that make client compatibility spotty, specifically 0.9 -> 1.0.
I'm getting some latency issues using data form CoreMotion roll, pitch and yaw properties from my device, every time that startDeviceMotionUpdatesToQueue() is called I emit this properties to my server but there is some lag even that I'm controlling the update interval to be fired 24 times per second when reseting the deviceMotionUpdateInterval property. Any change what is going wrong in here?
Thanks,
As someone new to iOS development and Swift, I could really use more Swift guidance and/or links to example code in the Readme.md
For example:
I getting the error "Could not connect to server" with iOS9. Please help me check.
On one hand, it is possible to emit an event by including any other parameters:
[socket emit: @"event_name", @1, @2, nil];
On the other hand, when an event and is received by a callback, only the first parameter is passed to it:
[socket on: @"event_name" callback: ^(id data) {}];
The expected behavior is all of the parameters to be passed to the callback as NSArray
.
Note that this is supported by the JavaScript client:
socket.on('event_name', function (first, second) {});
Hi
I'm developing an chat application on iOS using SocketIO, but i am not able to fine the cocoapod so as to install a pod for SIOSocket in the iOS app is there a pod for it, or do i have to go for any other alternative,
Thanks
Dear Sir/Madame.
I have one problem that related to SIOSocket. I cannot connect to server by this library. Could all of you tell me how connect it and receive data back. I spent much time on this. Thank you in advance!
Hello there,
I have an issue is when im testing the app in simulator, let me explain whats happening
When my app start´s I call a NSObject that handle my connection, and it's a shared object (static), so it handle all my connection thru all views.
Got a protocol to determinate when a message comes in then dispatch to the active view (subscribed one).
When I'm in simulator and minimize the App the application still connected to socket, and receive messages etc.. but when my app run into device it lost the connection (not showing message of disconnected) but simply cannot receive messages.
Any idea whats happening?
Thanks in advance.
When I try to emit an event to my SOCKET IO SERVER 1.1.0 all works well.
However, when I try to send data using a NSDictionary as the parameter, it does not work. Does the emit event support objects?
Hello!
I'm unable to receive socket events on iOS 8.
Here's my code:
#define socket_server @"http://127.0.0.1:4000"
static SIOSocket *globalSocket;
static NSString *socketID;
+ (void)connectToServer:(void (^)(BOOL))callback {
NSLog(@"Trying to connect to socket %@", socket_server);
[SIOSocket socketWithHost:socket_server response:^(SIOSocket *socket) {
globalSocket = socket;
[socket setOnConnect:^{
NSLog(@"Connected to server socket");
[self subscribeToSocketEvents];
callback(true);
}];
}];
}
+ (void) subscribeToSocketEvents {
NSLog(@"Subscribed to socket events");
[globalSocket on:@"socket-id" callback:^(NSArray *args) {
NSLog(@"Got socket ID: %@", args);
}];
}
io.on('connection', function(socket) {
console.log('New client connected with ID %s', socket.id);
emitSocketID(socket);
});
function emitSocketID(socket, callback) {
setTimeout(function() {
console.log('Sending socket ID to client');
socket.emit('socket-id', {socket: socket.id});
if (callback) { callback(); }
}, 500);
}
Additionally, if I make another node client (using socket.o-client
) it works properly:
socket = client('http://127.0.0.1:4000');
socket.on('socket-id', function(data) {
console.log('Got socket ID on public server: %s', JSON.stringify(data));
});
I'm going to keep looking at this- but if someone else sees the issue before I do that'd be awesome.
I'm using socket io 1.1.0. My app can connect, emit but not receive data from the server. Is the issue the socket io version?
I am a nodejs developer, I found a bug exist on your project:
I run the test with out modify, it test success
and socket.io log is look fine:
But when I change the localhost:3000
to my ip:3000
will would not work
I check the app.js server log, the server not show message emit log, only connect log
Then I upload the app.js to my server, and I change my local ip to server ip, it test failed too!
So i am thinking , is it the javascript cross-domain problem cause?
works fine with ip host
.
Thanks for your work
Just wondering why this would not work on iOS6, what is the dependency on iOS7?
Thanks.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.