B4A Library Socket.IO Client Library

Biswajit

Active Member
Licensed User
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

Last edited:

cinicalfoxOrion

New Member
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
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
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
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
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.
 
Top