I am trying to get the channel api working.
This is what I have so far:
in the view:
def channel_test(channel_token):
tries = 1
logging.info('starting channel_test')
for attempt in range(tries):
message = 'this is message number: ' + str(attempt)
channel.send_message(channel_token, message)
logging.info('just sent: ' + message)
logging.info(channel_token)
def viewfunc():
channel_token = channel.create_channel('aosasdf123')
deferred.defer(channel_test, channel_token, _countdown=10)
return render_template('Main/cycle.html', form=form, channel_token=channel_token)
and in my template:
<script type="text/javascript" charset="utf-8">
function tell_user(message) {
$('#CycleChannelMessages').append(message + '<br />');
}
function onOpened() {
console.log('onOpened');
var connected = true;
tell_user('ready to take messages');
tell_user('{{ channel_token }}');
}
function onMessage(msg_obj) {
console.log('onMessage');
tell_user('something');
// tell_user(msg_obj.data);
}
function onError(obj) {
console.log('onError');
}
function onClose(obj) {
console.log('onClose');
}
var channel = new goog.appengine.Channel('{{ channel_token }}');
var socket = channel.open();
socket.onopen = onOpened;
socket.onmessage = onMessage;
socket.onerror = onError;
socket.onclose = onClose;
</script>
But the only output I get is from onOpen:
ready to take messages
channel-1788270053-aosasdf123
And in the console I only see:
onOpened
So no other function has been run. The logs from the appengine launcher, clearly shows that the deferred function is being run and it is causing no errors or warnings.
Now what did I do wrong since nothing is showing up at the front-end.
This is on the dev-server BTW. I have not tried it in production yet.
Framework is Flask if that makes any difference.
You pass the client_id to send_message not the channel_token. So your code should be:
channel.send_message('aosasdf123', message)
You place the channel_token client-side for opening the channel, and keep the client_id secret on the server-side for transmitting messages to that client via the channel.
Related
I'm trying to find a way to emit from my client an instruction to the server which is inside a JSON object.
Here's my problem, my server receive my first instruction. But my second instruction 'deleteFile' is inside a json object,and the server never received this second instruction.
I would like to know if this is possible, and if i'm doing it in the wrong way.
I want to do something like this:
Client: I emit 'instruction' with my var "message"
service.deleteFile = function (peer, filename, callback) {
if (! LoginService.connected || ! LoginService.socket) {
console.log("deleteFile : not connected to server");
callback("no server");
var message = {
message : 'deleteFile',
dest_list : _.flattenDeep([peer]),
filename : filename,
};
LoginService.socket.emit('instruction',(message));
console.log("service.deleteFile : " , message);
callback(200);
};
And on server app.js for 'instruction':
socket.on('instruction', function(jsonMessage){
var dest_list = jsonMessage.dest_list;
var message = jsonMessage.message;
var filename = jsonMessage.filename;
var user_id = dest_list;
var instruction = {
message : message,
user_id : user_id,
filename : filename,
};
if (dest_list.length){
for (var i = 0; i < dest_list.length; i++) {
var user_id = dest_list[i].toLowerCase();
if (user_id in socket_clients){
var socketId = socket_clients[user_id].socketId;
socket.broadcast.to(socketId).emit('instruction', instruction);
console.log(instruction); //print "{message:'deleteFile', user_id: ['emitter'], filename: 'thegoodfile'}
}
else{
console.log("Error", user_id);
}
}
} else{
console.log("Error");
} });
Then on server app.js for 'deleteFile'(this instruction is inside my JSON object emited from client):
socket.on('deleteFile', function(jsonMessage) {
console.log("Test message"); };
I think my server don't understand my instruction 'deleteFile', but I don't find a way to tell him that it is an instruction.
Tell me if I missed some informations.
Thank you if you can help.
Found a solution with this post: socket, emit event to server from server
I can't send from my server to himself with 'broadcast'. From socket.io doc:
// sending to all clients except sender
socket.broadcast.emit('broadcast', 'hello friends!');
It was written ..
So I used Event handler in Node (doc: https://nodejs.org/api/events.html) and it works.
The following is my code, and I want to see the log in my stdout. My client is receiving message as publish and just echo back to server. I want to process that received message in python so that I want to store that value. How to able get the message value on stdout
var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://127.0.0.1',{
username: process.env.TOKEN
});
client.on('connect', function () {
console.log('connected');
client.subscribe('v1/devices/me/rpc/request/+')
});
client.on('message', function (topic, message) {
console.log('request.topic: ' + topic);
console.log('request.body: ' + message.toString());
var requestId = topic.slice('v1/devices/me/rpc/request/'.length);
//client acts as an echo service
client.publish('v1/devices/me/rpc/response/' + requestId, message);
});
You could just use process.stdout which used for this purpose https://nodejs.org/api/process.html#process_process_stdout
Im trying to send an answer to my websocket-server from a component which does not contain the websocket. My Websocket server looks like this:
componentDidMount() {
var ws = new WebSocket('ws:// URL');
ws.onmessage = this.handleMessage.bind(this);
...
}
How can I pass the "var ws" to another class or component. Or is it possible to make the websocket globally accessable?
Thank you very much for any help!
I found a solution with help from this question in stackoverflow:
visit:
React native: Always running component
I created a new class WebsocketController like this:
let instance = null;
class WebsocketController{
constructor() {
if(!instance){
instance = this;
}
this.ws = new WebSocket('ws://URL');
return instance;
}
}
export default WebsocketController
And then in my other class where I need my websocket I just called it like this:
let controller = new WebsocketController();
var ws = controller.ws;
websocket connection
keep this code in some file, name it with .js extenstion. ex: websocket.js
var WebSocketServer = require("ws").Server;
var wss = new WebSocketServer({port:8100});
wss.broadcast = function broadcast(msg) {
console.log(msg);
wss.clients.forEach(function each(client) {
client.send(msg);
});
};
wss.on('connection', function connection(ws) {
// Store the remote systems IP address as "remoteIp".
var remoteIp = ws.upgradeReq.connection.remoteAddress;
// Print a log with the IP of the client that connected.
console.log('Connection received: ', remoteIp);
ws.send('You successfully connected to the websocket.');
ws.on('message',wss.broadcast);
});
In your app/website side. create .js file. Ex: client.js
var SERVER_URL = 'ws://127.0.0.1:8100';
var ws;
function connect() {
//alert('connect');
ws = new WebSocket(SERVER_URL, []);
// Set the function to be called when a message is received.
ws.onmessage = handleMessageReceived;
// Set the function to be called when we have connected to the server.
ws.onopen = handleConnected;
// Set the function to be called when an error occurs.
ws.onerror = handleError;
}
function handleMessageReceived(data) {
// Simply call logMessage(), passing the received data.
logMessage(data.data);
}
function handleConnected(data) {
// Create a log message which explains what has happened and includes
// the url we have connected too.
var logMsg = 'Connected to server: ' + data.target.url;
// Add the message to the log.
logMessage(logMsg)
ws.send("hi am raj");
}
function handleError(err) {
// Print the error to the console so we can debug it.
console.log("Error: ", err);
}
function logMessage(msg) {
// $apply() ensures that the elements on the page are updated
// with the new message.
$scope.$apply(function() {
//Append out new message to our message log. The \n means new line.
$scope.messageLog = $scope.messageLog + msg + "\n";
});
}
Please let me know if you face any issue with this code
I get the message from client but in case of replying message, i tried many ways but no result .
My JavaScript Code is
var eb = new EventBus("http://localhost:8080/loginUrl");
eb.onopen = function () {
console.log("Connection Open")
};
eb.onclose = function () {
console.log("Connection Close")
};
eb.registerHandler("server-to-client", function (message) {
console.log('received a message: ' + message.body());
});
// publish a message
function sendMes(message){
console.log("Sending Message "+message);
eb.send("client-to-server",message,function(callback){
console.log("Received Message "+callback)
});
}
My Java Server Code is
Router router = Router.router(vertx);
vertx.createHttpServer().requestHandler(router::accept).listen(8080);
SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
BridgeOptions options = new BridgeOptions();
options.addInboundPermitted(new PermittedOptions().setAddress("client-to-server"));
options.addOutboundPermitted(new PermittedOptions().setAddress("server-to-client"));
sockJSHandler.bridge(options);
router.route("/loginUrl/*").handler(sockJSHandler);
EventBus eb = vertx.eventBus();
eb.consumer("client-to-server").handler(sockJSHand->{
System.out.println("Sending Message "+sockJSHand.body());//It prints the message from client
eb.send("server-to-client","Message");
});
How to reply back some message from server ?
Your code sample seems to be fine and almost looks like the chat server-client example application except that your should be using the EventBus#publish API instead of the EventBus#send API to allow the message to be dispatched among all registred handlers (all clients web browsers).
As per the Java docs:
EventBus publish(String address,
Object message)
Publish a message.
The message will be delivered to all handlers registered to the address.
An update of your server side code would be as follows:
Router router = Router.router(vertx);
vertx.createHttpServer().requestHandler(router::accept).listen(8080);
BridgeOptions options = new BridgeOptions();
options.addInboundPermitted(new PermittedOptions().setAddress("client-to-server"));
options.addOutboundPermitted(new PermittedOptions().setAddress("server-to-client"));
SockJSHandler sockJSHandler = SockJSHandler.create(vertx).bridge(options);
router.route("/loginUrl/*").handler(sockJSHandler);
EventBus eb = vertx.eventBus();
eb.consumer("client-to-server").handler(
sockJSHand -> {
System.out.println("Sending Message "+ sockJSHand.body());//It prints the message from client
eb.publish("server-to-client", "Message");
}
);
I need some help about my node.js+socket.io implementation.
This service expose a server that connects to an ActiveMQ broker over the STOMP protocol, using the stomp-js node.js module to receive events; that then are displayed in a web front end through websockets using socket.io.
So, everything was fine until I started use the Filters feature of ActiveMQ, but this was not the failure point because of my and my team researching, we found the way to ensure the implementation was fine, the problem comes with the connections: So here's the thing, I receive the filters to subscribe, I successfully subscribe to but when I receive a new set of filters is when comes the duplicated, triplicated and more and more messages depending the number of times that I subscribe-unsubscribe to.
So making some debug, I cannot see what's the problem but I'm almost sure that is some bad implementation of the callbacks or the program flow, I'll attach my code to read your comments about it.
Thanks a lot!
var sys = require('util');
var stomp = require('stomp');
var io = require('socket.io').listen(3000);
var socket = io.sockets.on('connection', function (socket) {
var stomp_args = {
port: 61616,
host: 'IP.ADDRESS',
debug: true,
};
var headers;
var client = new stomp.Stomp(stomp_args);
var setFilters = false;
socket.on('filtros', function (message) {
console.log('DEBUG: Getting filters');
if(setFilters){
client.unsubscribe(headers);
}
else{
client.connect();
}
var selector = '';
headers = '';
for(var attributename in message){
console.log(attributename+" : " + message[attributename]);
if(message[attributename] != ''){
selector += ' ' + attributename + '=\'' + message[attributename] + '\' AND ';
}
}
selector = selector.substring(0, selector.length - 4)
console.log('DEBUG: Selector String: ' + selector);
headers = {
destination: '/topic/virtualtopic',
ack: 'client',
selector: selector
};
if(setFilters)
client.subscribe(headers);
client.on('connected', function() {
client.subscribe(headers);
console.log('DEBUG: Client Connected');
setFilters = true;
});
});
var bufferMessage;
client.on('message', function(message) {
console.log("Got message: " + message.headers['message-id']);
var jsonMessage = JSON.parse(message.body);
if(bufferMessage === jsonMessage){
console.log('DEBUG: recibo un mensaje repetido');
return 0;
}
else{
console.log('DEBUG: Cool');
socket.emit('eventoCajero', jsonMessage);
}
client.ack(message.headers['message-id']);
bufferMessage = jsonMessage;
});
socket.on('disconnect', function(){
console.log('DEBUG: Client disconnected');
if(setFilters){
console.log('DEBUG: Consumer disconnected');
client.disconnect();
}
});
client.on('error', function(error_frame) {
console.log(error_frame.body);
});
});
Looking in the Socket.IO documentation, I've found that this is a known issue (I think critical known issue) and they have not fixed it yet. So, to correct this is necessary to reconnect to the socket in the client side to avoid duplicate messages, using:
socket.socket.reconnect();
function to force reconnection explicitly.