SockJs Eventbus Bridge: Restarting Verticle forces me to restart ClientHtml? - javascript

I build up with Vertx SockJs an Eventbus Bridge.
This is the code for my verticle:
#Override
public void start() throws Exception {
Router router = Router.router(vertx);
SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
BridgeOptions options = new BridgeOptions();
options.addInboundPermitted(new PermittedOptions().setAddress("test"));
options.addOutboundPermitted(new PermittedOptions().setAddress("test"));
options.addInboundPermitted(new PermittedOptions().setAddress("test2"));
options.addOutboundPermitted(new PermittedOptions().setAddress("test2"));
sockJSHandler.bridge(options);
router.route("/eventbus/*").handler(sockJSHandler);
vertx.createHttpServer().requestHandler(router::accept).listen(8600);
vertx.setTimer(5000, id -> {
vertx.eventBus().send("test", "hallo!", async -> {
if (async.succeeded()) {
System.out.println("Success!");
} else {
System.out.println("Failure!");
System.out.println(async.cause());
}
});
System.out.println("SEND!");
});
}
This is the code of ClientHtml:
var eb = new EventBus('http://localhost:8600/eventbus');
eb.onError=function() {
console.log('error');
}
eb.onopen = function() {
console.log('connected');
// set a handler to receive a message
eb.registerHandler('test', function(error, message) {
console.log('received a message: ' + JSON.stringify(message));
$( "#text" ).html(JSON.stringify(message));
});
eb.registerHandler('test2', function(error, message) {
console.log('received a message: ' + JSON.stringify(message));
console.log("Error: "+error);
$( "#text2" ).html(JSON.stringify(message));
});
}
eb.onclose = function() {
console.log("disconnected");
eb = null;
};
Now what Im concerned about:
After my verticle created a connection with the client, all is ok. But when Im restarting my verticle Im getting NO_HANDLER errors, because there is likely no new instance of Eventbus? Is there a way to handle this?

You can put your setup code in a method called after the page is loaded. In the onclose callback, cleanup all reply handlers (you will never get the server response) and call your setup method again.
function setupEventBus() {
var eb = new EventBus(window.location.protocol + "//" + window.location.host + "/eventbus");
eb.onclose = function (e) {
// Cleanup reply handlers
var replyHandlers = eb.replyHandlers;
for (var address in replyHandlers) {
if (replyHandlers.hasOwnProperty(address)) {
replyHandlers[address]({
failureCode: -1,
failureType: "DISCONNECT",
message: "EventBus closed"
});
}
}
// Setup the EventBus object again (after some time)
setTimeout(setupEventBus, 1000);
};
eb.onopen = function () {
// Register your handlers here
};
}

Related

I want to run this javascript code with NodeJS but I get this error if (!window.RTCPeerConnection) { ^ ReferenceError: window is not defined

This is my script js
I want to run this javascript code with NodeJS
but i get error
const JsSIP = require('jssip');
const NodeWebSocket = require('jssip-node-websocket');
const {execSync} = require('child_process');
JsSIP.debug.enable('*');
async function sleep(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
let socket = new NodeWebSocket('ws://192.168.90.27:8088/ws');
let ua = new JsSIP.UA(
{
sockets : [socket],
uri : 'sip:webrtc_client#192.168.90.27',
password : '123456',
display_name : 'webrtc_client'
});
ua.start();
ua.register();
ua.on('connected', function(e){ });
ua.on('disconnected', function(e){ });
ua.on('newRTCSession', function(e){ console.log(e) });
ua.on('newMessage', function(e){ console.log(e) });
// option for call
var eventHandlers = {
'progress': function(e) {
console.log('call is in progress');
},
'failed': function(e) {
console.log('call failed with cause: '+ e.data.cause);
},
'ended': function(e) {
console.log('call ended with cause: '+ e.data.cause);
},
'confirmed': function(e) {
console.log('call confirmed');
}
};
var options = {
'eventHandlers' : eventHandlers,
'mediaConstraints' : { 'audio': false, 'video': false }
};
// make a call
var session = ua.call('sip:100#192.168.90.27', options);
i want to make a call with asterisk server with JSsip lib
im trying to make a call with asterisk server with JSsip lib but i heard node js can not support WEBrtc and i want to know it this is correct ?
i installed packages like jssip node-jssip-websocket
how i can fix the problem ?
anybody can help me ?

How do I disconnect clients from the session with opentok?

Anytime I call the session.disconnect() method to remove clients from the session, I get this warning: "OpenTok:Publisher:warn Received connectivity event: "Cancel" without "Attempt"
and this error: "OpenTok:Subscriber:error Invalid state transition: Event 'disconnect' not possible in state 'disconnected'"
Could someone please explain to me what that error means? Thanks in advance.
// Initialize the session
var session = OT.initSession(data['apikey'], data['session_id']);
console.log(session);
// Initialize the publisher for the recipient
var publisherProperties = {insertMode: "append", width: '100%', height: '100%'};
var publisher = OT.initPublisher('publisher', publisherProperties, function (error) {
if (error) {
console.log(`Couldn't initialize the publisher: ${error}`);
} else {
console.log("Receiver publisher initialized.");
}
});
$('#session-modal').modal("show");
// Detect when new streams are created and subscribe to them.
session.on("streamCreated", function (event) {
console.log("New stream in the session");
var subscriberProperties = {insertMode: 'append', width: '100%', height: '100%'};
var subscriber = session.subscribe(event.stream, 'subscriber', subscriberProperties, function(error) {
if (error) {
console.log(`Couldn't subscribe to the stream: ${error}`);
} else {
console.log("Receiver subscribed to the sender's stream");
}
});
});
//When a stream you publish leaves a session, the Publisher object dispatches a streamDestroyed event:
publisher.on("streamDestroyed", function (event) {
console.log("The publisher stopped streaming. Reason: "
+ event.reason);
});
//When a stream, other than your own, leaves a session, the Session object dispatches a streamDestroyed event:
session.on("streamDestroyed", function (event) {
console.log("Stream stopped. Reason: " + event.reason);
session.disconnect();
console.log("called session.disconnect().");
});
session.on({
connectionCreated: function (event) {
connectionCount++;
if (event.connection.connectionId != session.connection.connectionId) {
console.log(`Another client connected. ${connectionCount} total.`);
}
},
connectionDestroyed: function connectionDestroyedHandler(event) {
connectionCount--;
console.log(`A client disconnected. ${connectionCount} total.`);
}
});
// Connect to the session
// If the connection is successful, publish an audio-video stream.
session.connect(data['token'], function(error) {
if (error) {
console.log("Error connecting to the session:", error.name, error.message);
} else {
console.log("Connected to the session.");
session.publish(publisher, function(error) {
if (error) {
console.log(`couldn't publish to the session: ${error}`);
} else {
console.log("The receiver is publishing a stream");
}
});
}
});
// Stop the publisher from streaming to the session if the user dismiss the modal
const stopSession = document.getElementById('stop-session');
stopSession.addEventListener("click", (event) => {
event.preventDefault();
session.disconnect();
});
I see this is kind of old, but wanted to share my solution to avoid this error. I'm not sure what the error means, but I call publisher.destroy() before calling session.disconnect() to avoid the error.
openTokPublisher.destroy();
openTokSession.disconnect();
I highly doubt you can disconnect the client with JavaScript. Here what I did.
// Connect to the session
session.connect(token, function connectCallback(error) {
// Get the connectionId
connectionId = session.connection.connectionId;
and use one of their SDK on the backend
https://tokbox.com/developer/sdks/server/
// Disconnect session
function disconnectSession() { // eslint-disable-line no-unused-vars
if (sessionId && connectionId) {
$.ajax({
url: '/OpenTok/DisconnectSession',
type: 'POST',
data: 'sessionId=' + sessionId + '&connectionId=' + connectionId,
});
}
}

websocket onclose not work in Java when client offline

I find websocket will closed when my client(Chrome 65.0.3325.181 windows10 x64) offline,this is I expected. But is not close in my server(JavaWeb project, Tomcat 7.0.79 & 8.5.24).
How can I close the websocket in server when the client offline?
JS code:
var ws;
var wsUrl = 'wss://' + location.host + '/test-websocket';
window.onload = function () {
createWebSocket(wsUrl);
};
window.onbeforeunload = function () {
ws.close();
};
function createWebSocket(url) {
ws = new WebSocket(url);
initEventHandle();
}
function initEventHandle() {
ws.onerror = function () {
console.log("error");
};
ws.onclose = function () {
console.log("close");
};
ws.onopen = function () {
setInterval(function () {
var message = {
id: "ping"
};
sendMessage(message);
}, 5000);
};
ws.onmessage = function (message) {
console.info('Received message: ' + message.data);
}
}
function sendMessage(message) {
const jsonMessage = JSON.stringify(message);
console.log('Senging message: ' + jsonMessage);
ws.send(jsonMessage);
}
Java Code:
private static final Gson GSON = new GsonBuilder().create();
#OnMessage
public void onMessage(String message, final Session session) throws IOException {
JsonObject jsonMessage = GSON.fromJson(message, JsonObject.class);
System.out.println(jsonMessage);
session.getBasicRemote().sendText("pong");
}
#OnError
public void onError(Throwable error) {
error.printStackTrace();
}
#OnClose
public void onClose(CloseReason reason) {
System.out.println(reason.toString());
}
In general close, for example close webpage, I can see "CloseReason: code [1000], reason [null]" in server output.
But when client offline, the onclose will work in client, log "close" in console. But nothing will print in server output.
This is why I think websocket onclose not work in Java when client offline.
So, how can I close the websocket in server when the client offline?

Unsubscribe from Rethink DB Outside function in Node.JS

Im using Socket.io and Rethink DB to push realtime data on Node.js.
Subscribing to the stream works but when the user disconnects I can figure out how to unsubscribe to the rethink db.
Here's my code:
Part of app.js:
// Adding socket.io
app.io = require('socket.io')();
var feed;
// On connection to the socket, just invoking the function.
app.io.on('connection',function(socket) {
console.log('Client connected...');
feed = require('./feed')(socket);
socket.on('disconnect', function() {
console.log('Got disconnect!');
# Here I'd like to unsubscribe
});
});
feed.js:
var r = require('rethinkdb');
var dbConfig = require('./config/database');
module.exports = function(socket) {
var connection = r.connect(dbConfig)
.then(function (connection) {
r.db('Minicall').table('Message').changes().run(connection,function(err,cursor) {
if(err) {
console.log(err);
}
cursor.each(function(err,row) {
console.log(JSON.stringify(row));
if(Object.keys(row).length > 0) {
console.log("send");
socket.emit("msgFeed",{"timestamp" : row.new_val.timestamp, "message" : row.new_val.message ,"ric" : row.new_val.ric});
}
});
});
});
};
So, how can I stop the subscribing (connection.stop()) when socket.on('disconnect') gets called? Probably a easy solution since I'm totally new to node and js.
You can have more than one event listener to an event, so in your cursor you'll add a disconnect event listener that can call cursor.close():
r.db('Minicall')
.table('Message')
.changes()
.run(connection, function(err, cursor) {
if(err) {
console.log(err);
}
cursor.each(function(err,row) {
console.log(JSON.stringify(row));
if(Object.keys(row).length > 0) {
console.log("send");
socket.emit("msgFeed",{"timestamp" : row.new_val.timestamp, "message" : row.new_val.message ,"ric" : row.new_val.ric});
}
});
socket.on('disconnect', function() {
cursor.close();
});
});

Intern Async call in before()

I need to request some json files that contain data I use for testing. I would like to make the request in the setup method, but there is no async method attached to it. When I run the code below, the log inside the test login function gets sent to the console before my logs from the setup method get sent. Is there a way I can tell setup to wait till my calls get completed before running the tests?
define([
'intern!object',
'pages/LoginPage',
'data-objects/DataFetcher'
], function(registerSuite, LoginPage, DataFetcher) {
registerSuite(function() {
var loginId = admin;
var password = test;
var regionData = US;
var loginPage = null;
return {
name: 'Login test',
setup: function() {
// Initialize page objects
loginPage = new LoginPage(this.remote, this.timeout);
// get test data
DataFetcher.getData(Pages.LoginPage).then(function(response) {
logger.info(DataFetcher.generateData(response));
});
DataFetcher.getData(Pages.TablePage).then(function(response) {
logger.info(DataFetcher.generateData(response));
});
DataFetcher.getData(Pages.PersonPage).then(function(response) {
logger.info(DataFetcher.generateData(response));
});
DataFetcher.getData(Pages.BasicInfoPage).then(function(response) {
logger.info(DataFetcher.generateData(response));
});
DataFetcher.getData(Pages.CompanyInfoPage).then(function(response) {
logger.info(DataFetcher.generateData(response));
});
},
login: function() {
logger.log('info', 'Login is ' + loginId + ' Password ' +
password);
return loginPage.load(regionData.BASE_URL)
.login(loginId, password)
.getAccumulatedState();
}
};
});
});
If you return a Promise from the setup function, Intern will wait for it to resolve before starting tests. You can return a Promise.all(...) of all your requests.

Categories