B4A Library Socket.IO Client Library

Hi everyone,

Here is the Socket.IO Client library wrap for this Github Project.
Click here for the B4i wrapper

SocketIOClient
Author:
@Biswajit
Version: 2.5
Dependency: OkHttpUtils2
  • SocketIOClient
    Method:
    • initialize(EventName As String)
    • connect (host As String, params As String, secure As Boolean)
    • connectWithOptions(host As String, params As String, secure As Boolean, reconnection As Boolean, reconnectionAttempts As Long, reconnectionDelay As Long, reconnectionDelayMax As Long, timeout As Long)
    • disconnect()
    • emit(event As String, data As Object)
    • addEvent(event As String, callback As String)
    • removeEvent(event As String, callback As String)
    • sendAck(ack As Object, data() As Object)
  • Events:
    • OnConnecting: will be raised at the first time it tries to connect to the server
    • OnConnectError(error As Object): will be raised if any error occurs when connecting
    • OnConnectionTimeout(timeout As Object): will be raised if the connection does not receive a response from the server after approximately 30 seconds
    • OnConnect: will be raised on successful connection
    • OnDisconnect(reason As Object): will be raised on connection disconnect. If the disconnection was initiated by the server, you need to reconnect manually else it will try itself to reconnect
    • OnReconnectAttempt(attemptNumber As Object): will be raised if it tries to reconnect after connection timeout or if connection disconnected from client side
    • OnReconnecting(attemptNumber As Object): will be raised on reconnection attempt
    • OnReconnect(attemptNumber As Object): will be raised on successful connection after connection timeout or if connection disconnected from client side
    • OnReconnectError(error As Object): will be raised if any error occurs when reconnecting
    • OnReconnectFailed: will be raised if when couldn’t reconnect within reconnectionAttempts
    • OnError(error As Object): will be raised if any error occurs

Example Attached.
For the server code you can check Socket.IO Github example or you can use this following chat server example (written in javascript) [attached]:

PHP:
var express = require('express');
var app = express();

// *** FOR HTTPS CONNECTION *** //
// const fs = require('fs');

// var options = {
//   key: fs.readFileSync('./key.pem'),
//   cert: fs.readFileSync('./cert.pem'),
//   passphrase: "password of cert/key file"
// };

// var server = require('https').createServer(options, app);
// *** FOR HTTPS CONNECTION *** //


// *** FOR HTTP CONNECTION *** //
var server = require('http').Server(app);
// *** FOR HTTP CONNECTION *** //

var io = require('socket.io')(server);
var users = {};


server.listen(999, function(){
  console.log('listening on *:999');
});

io.sockets.on('connection', function(socket){
    console.log("User Connected");

    socket.on('user_msg', function(data,callback){
        io.emit('new_message', data);
        callback("Data Received");
    });

    socket.on('disconnect', function(data){
        console.log('User disconnected');
    });
});

To run this example server code:
  1. Download NodeJS.
  2. Install it.
  3. Download library zip file and extract.
  4. Run cmd inside server folder
  5. Run npm install
  6. It will take some time to complete.
  7. After that run node app.js
  8. It will show listening on *:999
  9. Now create you app and connect.
  10. That's it!
  11. If you want to use HTTPS (secure connection) then for testing you can generate key and cert file using openssl
    Eg:
    openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365
Update v2:
  1. Now you can declare this in process_globals
  2. Some event signature has been modified (please check above)
  3. New event added OnError
Update v2.1:
  1. Conflict with B4A OkHttpUtils2 library (Fixed)
Update v2.2:
  1. Added support for a secure connection.
Update v2.3:
  1. Now you can detect data delivery via an acknowledgment of the emit event (Check Attached Example).
Update v2.4:
  1. Send acknowledgment with data to the server on receiving a message.
Update v2.5:
  1. Added query parameter support.
Update v2.6:
  1. Send any object instead of a string.
 

Attachments

  • Socket.IO-Simple-Example.zip
    9.8 KB · Views: 1,016
  • SocketIOClient_v2.6.zip
    159.2 KB · Views: 1,145
Last edited:
ocket.IO Client library wrap for this

Am very impressed that you develop this library for us.

but unfortunately, when I run your example , this gave me the following error:

io.socket.engineio.client.EngineIOException: xhr poll error.

I just modify this line of your very code:

socket io example:
Sub ConnectBtn_Click
    socket.initialize("socket")
    socket.connect("http://localhost:999","",False)
    'socket.connectWithOptions("http://localhost:999","{ rejectUnauthorized: false }", False,True, 0,1000,5000,20000) 'connect with options
    StatusLbl.Text = "Connecting"
End Sub

and this is my nodejs server running

server:
/*app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
  });*/
const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http);


io.on('connection', (socket) => {
  console.log('a user connected');
});

http.listen(999, () => {
  console.log('escuchando en el puerto *:999');
});

 
io.sockets.on('connection', function(socket){
    console.log("User Connected");

    socket.on('user_msg', function(data,callback){
        io.emit('new_message', data);
        callback("Data Received");
    });

    socket.on('disconnect', function(data){
        console.log('User disconnected');
    });
});

and this is my manifest

manifest:
AddManifestText(
<uses-sdk android:minSdkVersion="5" android:targetSdkVersion="29"/>
<uses-permission android:name="android.permission.INTERNET" />
<supports-screens android:largeScreens="true"
    android:normalScreens="true"
    android:smallScreens="true"
    android:anyDensity="true"/>)
SetApplicationAttribute(android:icon, "@drawable/icon")
SetApplicationAttribute(android:label, "$LABEL$")
SetApplicationAttribute(android:usesCleartextTraffic, "true")

CreateResourceFromFile(Macro, Themes.DarkTheme)


could you please help me to figure out whats wrong with my code?

best regards.
 

Biswajit

Active Member
Licensed User
Longtime User
Your server is running on the localhost (LAN) so you have to use the IP address of your pc like socket.connect("http://192.168.x.x:999","",False)
 

Biswajit

Active Member
Licensed User
Longtime User

Biswajit

Active Member
Licensed User
Longtime User
it there a way to get the socket ID when it get connected.I really need it
On successful connection just send the socket id from the server to the app simply just by emitting an event.
 

Carlos marin

Active Member
Licensed User
Longtime User
excellent thank you very much, works in b4j ?

it doesn't work either on b4a i have the same cinicalfoxOrion problem
 
Last edited:

Biswajit

Active Member
Licensed User
Longtime User
works in b4j ?
No. The library should work in b4j but the wrapper will not work as it's build for the b4a.
excellent thank you very much, works in b4j ?

it doesn't work either on b4a i have the same cinicalfoxOrion problem
On the server-side try to use express v4.13.4 and socket.io v1.4.5.
 

XorAndOr

Active Member
Licensed User
Longtime User
Hi, first of all thanks for the audio source
and sorry if I write here, then in case
I delete the post.
I ran the example and for once it worked fine.
After that I get this error and I don't know what it is.
p.s. I have not changed the source code
Thanks for the Help
B4X:
--------- beginning of /dev/log/main
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
Connecting...
status Connecting to server...
Connection established
status Registering Device...
status Connected. My ID: Tablet
** Activity (main) Pause, UserClosed = false **
** Activity (callactivity) Create, isFirst = true **
** Activity (callactivity) Resume **
starter_socket_audiorecived (java line: 205)
java.io.IOException
    at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:177)
    at libcore.io.Streams.readSingleByte(Streams.java:41)
    at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:130)
    at java.io.DataInputStream.readByte(DataInputStream.java:75)
    at anywheresoftware.b4a.randomaccessfile.B4XSerializator.readByte(B4XSerializator.java:150)
    at anywheresoftware.b4a.randomaccessfile.B4XSerializator.readObject(B4XSerializator.java:318)
    at anywheresoftware.b4a.randomaccessfile.B4XSerializator.ReadObject(B4XSerializator.java:129)
    at anywheresoftware.b4a.randomaccessfile.B4XSerializator.ConvertBytesToObject(B4XSerializator.java:99)
    at b4a.tabletaudio.starter._socket_audiorecived(starter.java:205)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at anywheresoftware.b4a.BA.raiseEvent2(BA.java:213)
    at anywheresoftware.b4a.BA.raiseEvent(BA.java:193)
    at com.biswajit.socketio.SocketIO$15.call(SocketIO.java:280)
    at io.socket.emitter.Emitter.emit(Emitter.java:117)
    at io.socket.client.Socket.onevent(Socket.java:340)
    at io.socket.client.Socket.onpacket(Socket.java:300)
    at io.socket.client.Socket.access$100(Socket.java:19)
    at io.socket.client.Socket$2$2.call(Socket.java:111)
    at io.socket.emitter.Emitter.emit(Emitter.java:117)
    at io.socket.client.Manager.ondecoded(Manager.java:407)
    at io.socket.client.Manager.access$1600(Manager.java:20)
    at io.socket.client.Manager$7.call(Manager.java:383)
    at io.socket.emitter.Emitter.emit(Emitter.java:117)
    at io.socket.parser.Parser$Decoder.add(Parser.java:168)
    at io.socket.client.Manager.ondata(Manager.java:403)
    at io.socket.client.Manager.access$1100(Manager.java:20)
    at io.socket.client.Manager$2.call(Manager.java:352)
    at io.socket.emitter.Emitter.emit(Emitter.java:117)
    at io.socket.engineio.client.Socket.onPacket(Socket.java:511)
    at io.socket.engineio.client.Socket.access$1000(Socket.java:31)
    at io.socket.engineio.client.Socket$5.call(Socket.java:313)
    at io.socket.emitter.Emitter.emit(Emitter.java:117)
    at io.socket.engineio.client.Transport.onPacket(Transport.java:134)
    at io.socket.engineio.client.Transport.onData(Transport.java:130)
    at io.socket.engineio.client.transports.WebSocket.access$200(WebSocket.java:24)
    at io.socket.engineio.client.transports.WebSocket$2$3.run(WebSocket.java:112)
    at io.socket.thread.EventThread$2.run(EventThread.java:80)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
    at java.lang.Thread.run(Thread.java:841)
Caused by: java.util.zip.DataFormatException: incorrect header check
    at java.util.zip.Inflater.inflateImpl(Native Method)
    at java.util.zip.Inflater.inflate(Inflater.java:228)
    at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:158)
    ... 40 more
Disconnected
 

Biswajit

Active Member
Licensed User
Longtime User
Hi, first of all thanks for the audio source
and sorry if I write here, then in case
I delete the post.
I ran the example and for once it worked fine.
After that I get this error and I don't know what it is.
p.s. I have not changed the source code
Thanks for the Help
B4X:
--------- beginning of /dev/log/main
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
Connecting...
status Connecting to server...
Connection established
status Registering Device...
status Connected. My ID: Tablet
** Activity (main) Pause, UserClosed = false **
** Activity (callactivity) Create, isFirst = true **
** Activity (callactivity) Resume **
starter_socket_audiorecived (java line: 205)
java.io.IOException
    at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:177)
    at libcore.io.Streams.readSingleByte(Streams.java:41)
    at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:130)
    at java.io.DataInputStream.readByte(DataInputStream.java:75)
    at anywheresoftware.b4a.randomaccessfile.B4XSerializator.readByte(B4XSerializator.java:150)
    at anywheresoftware.b4a.randomaccessfile.B4XSerializator.readObject(B4XSerializator.java:318)
    at anywheresoftware.b4a.randomaccessfile.B4XSerializator.ReadObject(B4XSerializator.java:129)
    at anywheresoftware.b4a.randomaccessfile.B4XSerializator.ConvertBytesToObject(B4XSerializator.java:99)
    at b4a.tabletaudio.starter._socket_audiorecived(starter.java:205)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at anywheresoftware.b4a.BA.raiseEvent2(BA.java:213)
    at anywheresoftware.b4a.BA.raiseEvent(BA.java:193)
    at com.biswajit.socketio.SocketIO$15.call(SocketIO.java:280)
    at io.socket.emitter.Emitter.emit(Emitter.java:117)
    at io.socket.client.Socket.onevent(Socket.java:340)
    at io.socket.client.Socket.onpacket(Socket.java:300)
    at io.socket.client.Socket.access$100(Socket.java:19)
    at io.socket.client.Socket$2$2.call(Socket.java:111)
    at io.socket.emitter.Emitter.emit(Emitter.java:117)
    at io.socket.client.Manager.ondecoded(Manager.java:407)
    at io.socket.client.Manager.access$1600(Manager.java:20)
    at io.socket.client.Manager$7.call(Manager.java:383)
    at io.socket.emitter.Emitter.emit(Emitter.java:117)
    at io.socket.parser.Parser$Decoder.add(Parser.java:168)
    at io.socket.client.Manager.ondata(Manager.java:403)
    at io.socket.client.Manager.access$1100(Manager.java:20)
    at io.socket.client.Manager$2.call(Manager.java:352)
    at io.socket.emitter.Emitter.emit(Emitter.java:117)
    at io.socket.engineio.client.Socket.onPacket(Socket.java:511)
    at io.socket.engineio.client.Socket.access$1000(Socket.java:31)
    at io.socket.engineio.client.Socket$5.call(Socket.java:313)
    at io.socket.emitter.Emitter.emit(Emitter.java:117)
    at io.socket.engineio.client.Transport.onPacket(Transport.java:134)
    at io.socket.engineio.client.Transport.onData(Transport.java:130)
    at io.socket.engineio.client.transports.WebSocket.access$200(WebSocket.java:24)
    at io.socket.engineio.client.transports.WebSocket$2$3.run(WebSocket.java:112)
    at io.socket.thread.EventThread$2.run(EventThread.java:80)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
    at java.lang.Thread.run(Thread.java:841)
Caused by: java.util.zip.DataFormatException: incorrect header check
    at java.util.zip.Inflater.inflateImpl(Native Method)
    at java.util.zip.Inflater.inflate(Inflater.java:228)
    at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:158)
    ... 40 more
Disconnected
As per the error log,

B4X:
Connection established
status Registering Device...
status Connected. My ID: Tablet <--
It seems like you have changed something. As this "My ID" should show a unique generated ID with an underscore character. Do not change the id generation process as this is how the server has been configured. If you change you should generate a unique ID for your device on startup. Because the same id will replace the socket from the server memory and that will cause communication issue
 
Last edited:

ilan

Expert
Licensed User
Longtime User
hi @Biswajit

today i came across Socket.IO and was wondering if someone had wrapped it for b4x and you did so thank you very much for that.
i have downloaded the latest source from GitHub and i am able to run the chat server example and connect to it via web browser unfortunately i am not able to connect via b4a.

the message i get is:

*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
Connecting...
io.socket.engineio.client.EngineIOException: xhr poll error
Tring to Reconnect
Reconnecting
io.socket.engineio.client.EngineIOException: xhr poll error
Reconnection Error
Tring to Reconnect
Reconnecting
io.socket.engineio.client.EngineIOException: xhr poll error
Reconnection Error

it always tries to reconnect but cannot. i have changed the IP according to my pc and also updated the Port according to the downloaded chat server js file.

i need to mention that i am using the Emulator. Should i try on a real device?
i see other people complaining about the same Error message i get.

nodejs server file:

B4X:
// Setup basic express server
const express = require('express');
const app = express();
const path = require('path');
const server = require('http').createServer(app);
const io = require('socket.io')(server);
const port = process.env.PORT || 3000;

server.listen(port, () => {
  console.log('Server listening at port %d', port);
});

// Routing
app.use(express.static(path.join(__dirname, 'public')));

// Chatroom

let numUsers = 0;

io.on('connection', (socket) => {
  let addedUser = false;

  // when the client emits 'new message', this listens and executes
  socket.on('new message', (data) => {
    // we tell the client to execute 'new message'
    socket.broadcast.emit('new message', {
      username: socket.username,
      message: data
    });
  });

  // when the client emits 'add user', this listens and executes
  socket.on('add user', (username) => {
    if (addedUser) return;

    // we store the username in the socket session for this client
    socket.username = username;
    ++numUsers;
    addedUser = true;
    socket.emit('login', {
      numUsers: numUsers
    });
    // echo globally (all clients) that a person has connected
    socket.broadcast.emit('user joined', {
      username: socket.username,
      numUsers: numUsers
    });
  });

  // when the client emits 'typing', we broadcast it to others
  socket.on('typing', () => {
    socket.broadcast.emit('typing', {
      username: socket.username
    });
  });

  // when the client emits 'stop typing', we broadcast it to others
  socket.on('stop typing', () => {
    socket.broadcast.emit('stop typing', {
      username: socket.username
    });
  });

  // when the user disconnects.. perform this
  socket.on('disconnect', () => {
    if (addedUser) {
      --numUsers;

      // echo globally that this client has left
      socket.broadcast.emit('user left', {
        username: socket.username,
        numUsers: numUsers
      });
    }
  });
});
 

Biswajit

Active Member
Licensed User
Longtime User
hi @Biswajit

today i came across Socket.IO and was wondering if someone had wrapped it for b4x and you did so thank you very much for that.
i have downloaded the latest source from GitHub and i am able to run the chat server example and connect to it via web browser unfortunately i am not able to connect via b4a.

the message i get is:



it always tries to reconnect but cannot. i have changed the IP according to my pc and also updated the Port according to the downloaded chat server js file.

i need to mention that i am using the Emulator. Should i try on a real device?
i see other people complaining about the same Error message i get.

nodejs server file:

B4X:
// Setup basic express server
const express = require('express');
const app = express();
const path = require('path');
const server = require('http').createServer(app);
const io = require('socket.io')(server);
const port = process.env.PORT || 3000;

server.listen(port, () => {
  console.log('Server listening at port %d', port);
});

// Routing
app.use(express.static(path.join(__dirname, 'public')));

// Chatroom

let numUsers = 0;

io.on('connection', (socket) => {
  let addedUser = false;

  // when the client emits 'new message', this listens and executes
  socket.on('new message', (data) => {
    // we tell the client to execute 'new message'
    socket.broadcast.emit('new message', {
      username: socket.username,
      message: data
    });
  });

  // when the client emits 'add user', this listens and executes
  socket.on('add user', (username) => {
    if (addedUser) return;

    // we store the username in the socket session for this client
    socket.username = username;
    ++numUsers;
    addedUser = true;
    socket.emit('login', {
      numUsers: numUsers
    });
    // echo globally (all clients) that a person has connected
    socket.broadcast.emit('user joined', {
      username: socket.username,
      numUsers: numUsers
    });
  });

  // when the client emits 'typing', we broadcast it to others
  socket.on('typing', () => {
    socket.broadcast.emit('typing', {
      username: socket.username
    });
  });

  // when the client emits 'stop typing', we broadcast it to others
  socket.on('stop typing', () => {
    socket.broadcast.emit('stop typing', {
      username: socket.username
    });
  });

  // when the user disconnects.. perform this
  socket.on('disconnect', () => {
    if (addedUser) {
      --numUsers;

      // echo globally that this client has left
      socket.broadcast.emit('user left', {
        username: socket.username,
        numUsers: numUsers
      });
    }
  });
});
The underlying socket.io sdk supports express v4.13.4 and socket.io v1.4.5. The sdk depends on the ok.io library. Some B4A internal libraries are also depends on a specific version of ok.io. So to make this wrapper compatible with the existing ok.io I had to wrap the older sdk.

On the server-side use express v4.13.4 and socket.io v1.4.5 and it will work.

I noticed that you are using a different port and different eventname on the server code. Make sure you have changed the same on the B4A code.

Note: if you are running the server on localhost then make sure that the emulator has access to your localhost/local ip. Else it will not work.

I will check and try to wrap a newer sdk if that supports the internal ok.io.
 

ilan

Expert
Licensed User
Longtime User
Note: if you are running the server on localhost then make sure that the emulator has access to your localhost/local ip. Else it will not work.

I will check and try to wrap a newer sdk if that supports the internal ok.io.

yes i made sure that i can access my localhost ip from the emulator and i have changed the events and the port. i guess its because a different express and socket.io version.

anyway thank you i will wait for the update :)
 

cheveguerra

Member
Licensed User
Longtime User
Hi,

I installed Nodejs, Express v4.13.4 and socket.io v1.4.5. , and when execute "node app.js" I get the "Listening on *:999", BUT when I run the app I get this error:

B4X:
Connecting...
main_socket_onconnect (java line: 451)
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
    at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:9444)
    at android.view.ViewRootImpl.focusableViewAvailable(ViewRootImpl.java:4548)
    at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:928)
    at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:928)
    at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:928)
    at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:928)
    at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:928)
    at android.view.View.setFlags(View.java:15709)
    at android.view.View.setEnabled(View.java:10826)
    at android.widget.TextView.setEnabled(TextView.java:2469)
    at anywheresoftware.b4a.objects.ViewWrapper.setEnabled(ViewWrapper.java:278)
    at b4a.example.main._socket_onconnect(main.java:451)
    at java.lang.reflect.Method.invoke(Native Method)
    at anywheresoftware.b4a.BA.raiseEvent2(BA.java:213)
    at anywheresoftware.b4a.BA.raiseEvent(BA.java:193)
    at com.biswajit.socketio.SocketIO$4.call(SocketIO.java:131)
    at io.socket.emitter.Emitter.emit(Emitter.java:117)
    at io.socket.client.Socket.access$601(Socket.java:19)
    at io.socket.client.Socket$5.run(Socket.java:177)
    at io.socket.thread.EventThread.exec(EventThread.java:55)
    at io.socket.client.Socket.emit(Socket.java:173)
    at io.socket.client.Socket.onconnect(Socket.java:387)
    at io.socket.client.Socket.onpacket(Socket.java:287)
    at io.socket.client.Socket.access$100(Socket.java:19)
    at io.socket.client.Socket$2$2.call(Socket.java:111)
    at io.socket.emitter.Emitter.emit(Emitter.java:117)
    at io.socket.client.Manager.ondecoded(Manager.java:407)
    at io.socket.client.Manager.access$1600(Manager.java:20)
    at io.socket.client.Manager$7.call(Manager.java:383)
    at io.socket.emitter.Emitter.emit(Emitter.java:117)
    at io.socket.parser.Parser$Decoder.add(Parser.java:157)
    at io.socket.client.Manager.ondata(Manager.java:399)
    at io.socket.client.Manager.access$1000(Manager.java:20)
    at io.socket.client.Manager$2.call(Manager.java:350)
    at io.socket.emitter.Emitter.emit(Emitter.java:117)
    at io.socket.engineio.client.Socket.onPacket(Socket.java:511)
    at io.socket.engineio.client.Socket.access$1000(Socket.java:31)
    at io.socket.engineio.client.Socket$5.call(Socket.java:313)
    at io.socket.emitter.Emitter.emit(Emitter.java:117)
    at io.socket.engineio.client.Transport.onPacket(Transport.java:134)
    at io.socket.engineio.client.transports.Polling.access$700(Polling.java:17)
    at io.socket.engineio.client.transports.Polling$2.call(Polling.java:124)
    at io.socket.engineio.parser.Parser.decodePayload(Parser.java:251)
    at io.socket.engineio.client.transports.Polling._onData(Polling.java:134)
    at io.socket.engineio.client.transports.Polling.onData(Polling.java:106)
    at io.socket.engineio.client.transports.PollingXHR$5$1.run(PollingXHR.java:111)
    at io.socket.thread.EventThread$2.run(EventThread.java:80)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at java.lang.Thread.run(Thread.java:764)
** Activity (main) Pause, UserClosed = true **

Any idea what a I doing wrong? :(
 

cheveguerra

Member
Licensed User
Longtime User
Sorry, missing information, the app starts, but when I click on connect is when the error occurs, the server says that the user is connected, but the app gives that error.
 

cheveguerra

Member
Licensed User
Longtime User
If I enable all the buttons on the layout and comment all the lines that enable or disable the buttons, then the app does not crash, I can connect and disconnect without problem, but when I try to send some text, I get this error:

B4X:
Disconnected
Connecting...
Connection established
Disconnected
Connecting...
Connection established
Disconnected
Connecting...
Connection established
java.lang.Exception: Sub socket_notify signature does not match expected signature.
    at anywheresoftware.b4a.BA.raiseEvent2(BA.java:215)
    at anywheresoftware.b4a.BA.raiseEvent(BA.java:193)
    at com.biswajit.socketio.SocketIO$15.call(SocketIO.java:280)
    at io.socket.emitter.Emitter.emit(Emitter.java:117)
    at io.socket.client.Socket.onevent(Socket.java:340)
    at io.socket.client.Socket.onpacket(Socket.java:293)
    at io.socket.client.Socket.access$100(Socket.java:19)
    at io.socket.client.Socket$2$2.call(Socket.java:111)
    at io.socket.emitter.Emitter.emit(Emitter.java:117)
    at io.socket.client.Manager.ondecoded(Manager.java:407)
    at io.socket.client.Manager.access$1600(Manager.java:20)
    at io.socket.client.Manager$7.call(Manager.java:383)
    at io.socket.emitter.Emitter.emit(Emitter.java:117)
    at io.socket.parser.Parser$Decoder.add(Parser.java:157)
    at io.socket.client.Manager.ondata(Manager.java:399)
    at io.socket.client.Manager.access$1000(Manager.java:20)
    at io.socket.client.Manager$2.call(Manager.java:350)
    at io.socket.emitter.Emitter.emit(Emitter.java:117)
    at io.socket.engineio.client.Socket.onPacket(Socket.java:511)
    at io.socket.engineio.client.Socket.access$1000(Socket.java:31)
    at io.socket.engineio.client.Socket$5.call(Socket.java:313)
    at io.socket.emitter.Emitter.emit(Emitter.java:117)
    at io.socket.engineio.client.Transport.onPacket(Transport.java:134)
    at io.socket.engineio.client.Transport.onData(Transport.java:126)
    at io.socket.engineio.client.transports.WebSocket.access$100(WebSocket.java:24)
    at io.socket.engineio.client.transports.WebSocket$2$2.run(WebSocket.java:99)
    at io.socket.thread.EventThread$2.run(EventThread.java:80)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at java.lang.Thread.run(Thread.java:764)
** Activity (main) Pause, UserClosed = true **

This is the code that I have, I just modified the server IP and the secure parameter to False

B4X:
#Region  Project Attributes
    #ApplicationLabel: Socket.IO Simple Example
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
    #BridgeLogger : True
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.

End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.
    Dim socket As SocketIOClient
    Private StatusLbl As Label
    Private SendBtn As Button
    Private AckLbl As Label
    Private MsgInput As EditText
    Private ConnectBtn As Button
    Private DisconnectBtn As Button
End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    Activity.LoadLayout("Layout1")
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)
    
End Sub

Sub ConnectBtn_Click
    socket.initialize("socket")
    socket.connect("http://11.0.0.139:999/","",False)
    'socket.connectWithOptions("https://192.168.0.103:999/","", True,True, 0,1000,5000,20000) 'connect with options
    StatusLbl.Text = "Connecting"
End Sub

Sub DisconnectBtn_Click
    socket.disconnect()
    StatusLbl.Text = "Disconnecting"
End Sub

Sub socket_OnConnect
    socket.addEvent("new_message","notify")
    StatusLbl.Text = "Connected"
'    DisconnectBtn.Enabled = True
'    Log("DisconnectBtn enable true")
'    SendBtn.Enabled = True
'    Log("SendBtn enable true")
'    MsgInput.Enabled = True
'    Log("MsgInput enable true")
'    ConnectBtn.Enabled = False
'    Log("ConnectBtn enable false")
End Sub

Sub socket_OnDisconnect(Reason As Object)
    socket.removeEvent("new_message","notify")
    StatusLbl.Text = "Disconnected"
'    ConnectBtn.Enabled = True
'    Log("ConnectBtn enable true")
''    SendBtn.Enabled = False
'    Log("SendBtn enable true")
'    MsgInput.Enabled = False
'    Log("SendBtn enable false")
'    DisconnectBtn.Enabled = False
'    Log("DisconnectBtn enable false")
End Sub

Sub socket_notify(message As Object, ack As Object)
    socket.sendAck(ack,Array("your data"))
    Log(message)
End Sub

Sub SendBtn_Click
    socket.emit("user_msg",MsgInput.Text)
End Sub

Sub user_msg_ack(data As Object)
    AckLbl.Text = data
End Sub
 

Biswajit

Active Member
Licensed User
Longtime User
Sorry, missing information, the app starts, but when I click on connect is when the error occurs, the server says that the user is connected, but the app gives that error.
Is it happening on debug mode or release mode?

Sub socket_notify signature does not match expected signature.
If the server sends an ack object along with the message then you can use
Sub socket_notify(message As Object, ack As Object)

if the server sends only message then the signature will be
Sub socket_notify(message As Object)

Check your server code.
 
Top