npm install nativescript-socketio
or
tns plugin add nativescript-socketio
Set connection string and options then connect
var SocketIO = require('nativescript-socketio').SocketIO;
var socketIO = new SocketIO(url, opts);
Alternatively:
import { SocketIO } from 'nativescript-socketio';
var socketIO = new SocketIO(url, opts);
Connect to server
socketIO.connect()
Send data to the server
socketIO.emit(event,data)
Listen for data
socketIO.on(event,callback)
Set instance
new SocketIO(null,null,oldInstance)
// app.module.ts
import { SocketIOModule } from "nativescript-socketio/angular";
@NgModule({
imports: [
SocketIOModule.forRoot(server),
]
})
// app.component.ts
import { Component, OnInit, OnDestroy } from "@angular/core";
import { SocketIO } from "nativescript-socketio";
@Component({
// ...
})
export class AppComponent implements OnInit, OnDestroy {
constructor(private socketIO: SocketIO) { }
ngOnInit() {
this.socketIO.connect();
}
ngOnDestroy() {
this.socketIO.disconnect();
}
}
// test.component.ts
import { Component, OnInit, NgZone } from "@angular/core";
import { SocketIO } from "nativescript-socketio";
@Component({
// ...
})
export class TestComponent implements OnInit {
constructor(
private socketIO: SocketIO,
private ngZone: NgZone
) { }
ngOnInit() {
this.socketIO.on("test", data => {
this.ngZone.run(() => {
// Do stuff here
});
});
}
test() {
this.socketIO.emit("test", { test: "test" });
}
}
Start socketio server
cd demo/demo-server
npm install
node app