socket.on() not receiving data - javascript

I am having a problem with getting socket.on to work
$('#showmsg').click(function() {
var socket = io.connect('http://localhost:3000');
var msgText = $('#msgtext');
socket.emit('show msg', msgText.val());
});
That code works, as shown by using
io.sockets.on('connection', function(socket) {
socket.on('show msg', function(data) {
console.log(data);
});
});
in server.js, my main app file, however in another file, when I use the code
$(document).ready(function (){
var socket = io.connect();
socket.on('show msg', function(data) {
$('#container').hide();
});
});
Nothing happens. Does anyone know how I can get this code to work?

When you connect in the client, you have to wait for the connect message before you can send data with .emit(). As you have it now, you are trying to send the data before the connection has finished so the data is lost.
See the client-side example here: http://socket.io/docs/#sending-and-getting-data-(acknowledgements)

I think what's happening is that in your document.ready function, you are trying to call io.connect() but you are then calling the show message before your socket has connected. Try doing it like this
socket.on('connect', function (){
socket.on('show msg', function(data) {
$('#container').hide();
});
});

Nothing happens because you don't emit anything.
$(document).ready(function (){
var socket = io.connect('http://localhost:3000');
socket.on('show msg', function(data) {
$('#container').hide();
});
socket.emit('show msg', 'right now I am emitting data');
});

Related

Why my messages are being displayed many times?

I made a chat room using electron. But when I send a message to the server and from there the message will be displayed to the users for some reason the message is being displayed multiple times. Example: I send -> "hello" the message will be displayed once, when I send a second message ->"Hello server" the message will be display two times, when I sent a third message ->"ok" this message will be displayed three times. The fourth message will be displayed 4 times etc.
this is the renderer.js code:
const ws = new WebSocket("ws://127.0.0.1:5000");
ws.addEventListener('open', function(event){
ws.send('hello server');
console.log("data sent");
});
function send_data(){
console.log("button clicked");
ws.send(document.getElementById("input_text").value);
ws.addEventListener('message', function(event){
console.log("server send something");
let mess=event.data;
console.log(mess);
update_chat(mess);
});
};
function update_chat(mess){
const div = document.createElement('div');
div.classList.add('message');
div.innerHTML = `okwpegjwpgj said: ${mess}`;
document.querySelector('.chat_messages').appendChild(div);
}
this is the server.js code:
const WebSocket = require('ws');
let broadcast_msg;
const PORT = 5000;
const wss = new WebSocket.Server({
port: PORT
});
wss.on("connection", ws =>{
ws.on('message', function incoming(message){
broadcast_msg=message;
console.log('received: ', message);
ws.send(message);
});
});
console.log("Server is liestening on port " + PORT);
Because you add the addEventListener('message') on every send_data() call.
Add the eventlistener once and remove it from the send_data() method. you don't need to add a new eventlistener every time you send data.
ws.addEventListener('message', function(event){
console.log("server send something");
let mess=event.data;
console.log(mess);
update_chat(mess);
});
function send_data(){
console.log("button clicked");
ws.send(document.getElementById("input_text").value);
};
Change your renderer.js file to this:
const ws = new WebSocket("ws://127.0.0.1:5000");
ws.addEventListener('open', function(event){
ws.send('hello server');
console.log("data sent");
});
ws.addEventListener('message', function(event){
console.log("server send something");
let mess=event.data;
console.log(mess);
update_chat(mess);
});
function send_data(){
console.log("button clicked");
ws.send(document.getElementById("input_text").value);
};
function update_chat(mess){
const div = document.createElement('div');
div.classList.add('message');
div.innerHTML = `okwpegjwpgj said: ${mess}`;
document.querySelector('.chat_messages').appendChild(div);
}

Execute a function when a nodejs event is received

I might missing something basic, but here is my goal: I have a small instant chat example based on tutorial found here Instant Chat for drupal
The principle is to connect to a nodejs server that basically just broadcast all messages it receives.
I have this function on the client side (inside a drupal tpl.php file):
(function($) {
var myNick = 'me';
var socket = io.connect('http://<?php print $_SERVER['SERVER_ADDR'] ?>:8081');
socket.on('connect', function() {
$('#chat').addClass('connected');
});
socket.on('user message', message);
function message(from, msg) {
if (msg == 'GO') {
** EXECUTE A FUNCTION HERE **
} else { //display the message and sender
$('#lines').append($('<p>').append(from, msg));
}
}
$(document).ready(function() {
$('#send-message').submit(function() {
message(myNick, $('#messageinput').val());
socket.emit('user message', $('#messageinput').val());
clear();
$('#lines').get(0).scrollTop = 10000000;
return false;
});
function clear() {
$('#message').val('').focus();
};
});
})(jQuery);
When I send a message with content =GO, the submit is executed, the message(..,..) function is called and my specific function is executed properly.
But when I receive a GO message, the socket.on event triggers, message() function is called, but my specific function is NOT executed.
Any Idea how I can fix this?
Many thanks for your help.
Michael.

With a chrome extension, how do I pass a message from background script to content script using a long-lived connection (port)?

Here is my background script. I am able to send a message to it from my popup script. In other words, the console logs "hello" in the background page.
// background.js
chrome.runtime.onConnect.addListener(function(port){
port.onMessage.addListener(function(msg) {
if (msg.greeting == "hello") {
var port = chrome.tabs.connect(0, {name: "mycontentscript"});
port.postMessage({greeting:"hello"});
console.log('hello');
}
});
});
However, I cannot get the message from the background script to my content script. Here is my content script. The alert is not showing.
// content.js
var port = chrome.runtime.connect({name:"mycontentscript"});
port.onMessage.addListener(function(message,sender){
if (message.greeting == "hello") {
alert('hello');
}
});
What am I doing wrong? Thanks.
It seems you forgot establishing the connection, just postMessage in content script after the port is created, and reuse the port in runtime.onConnect.addListener() in background page.
background.js
chrome.runtime.onConnect.addListener(function(port) {
port.onMessage.addListener(function(msg) {
if (msg.greeting == "hello") {
port.postMessage({ greeting: "hello" });
console.log('hello');
}
});
});
content.js
var port = chrome.runtime.connect({ name: "mycontentscript" });
port.postMessage({greeting: "hello"});
port.onMessage.addListener(function(message) {
if (message.greeting == "hello") {
alert('hello');
}
});
I don't know if my situation is exactly like yours, but I also wrote a Chrome extension in which the background page sends a message to the client.
In my content script, I do the following:
chrome.runtime.sendMessage('requestData', this.updateData.bind(this));
In my background script, I have:
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
sendResponse({
messages : inboxMessages,
userId : user_id
});
});
And then my content script receives the message:
this.updateData = function(data) {
//...
}
Hopefully that helps you!
In the background.js:
chrome.runtime.onConnect.addListener(function(port){//here you've got the port
port.onMessage.addListener(function(msg) {
if (msg.greeting == "hello") {
//and here you're making a new, unneeded port, for which nobody is listening.
//Use the one you've got.
var port = chrome.tabs.connect(0, {name: "mycontentscript"});
port.postMessage({greeting:"hello"});
console.log('hello');
}
});
});
Either initiate the connect from background with chrome.tabs.connect, and put chrome.runtime.onConnect listener in the tab's content.js, or initiate the connect from the tab, as you did, and use the port obtained in the background's onConnect listener. Just delete that
var port=chrome.tabs.connect(0, {name: "mycontentscript});
line.

Sorting socketing queries with IF statements?

(ws for node.js)
Like this;
socketserver.on('connection', function(socket) {
socket.on('message', function(data) {
// This is in eventone.html on /eventone
if(data == 'eventone') {
console.log("Event one triggered!");
socket.send(foo);
socket.close();
}
// This is in eventtwo.html on /eventtwo
if(data == 'eventtwo') {
console.log("Event two triggered!");
socket.send(bar);
socket.close();
}
// This is in eventthree.html on /eventthree
if(data == 'eventthree') {
console.log("Event three triggered!");
socket.send(foobar);
socket.close();
}
});
});
Is this a good idea for socketing data through one socketserver across different pages?
I want 'foo' to get sent to eventone.html, 'bar' to eventtwo.html and 'foobar' to eventthree.html, which are loaded on the client side, whenever the client sends the respective event through a button press (or whatever).
If this is a good idea, why would you ever use static routing and such things with request and response, why not just send everything through a socket?

Nodejs, express & socket.io communicate between two static client pages

i am trying to build a remote for a gallery by using nodejs, express & socket.io.
the structure is as follows
/index.js
/public/screen.html
/screen.js
/remote.html
/remote.js
the idea is to have a gallery of images displayed on remote.html, select one and send the selected index to screen.html by using socket.io.
as of now my code looks like this:
index.js
var express = require('express');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io').listen(server);
app.use(express.static('public'));
server.listen(8080, function(){
// setup image gallery and stuff...
connectToServer();
});
remote.js
var socket = null;
document.addEventListener("DOMContentLoaded", function(event) {
//some stuff
connectToServer();
});
function showImage (index){ //called by events
console.log('selected incdex: ' + index);
if(socket != null) {
socket.emit('selection', {id: index});
};
}
function connectToServer(){
socket = io.connect('http://localhost:8080');
socket.on('connection', function (socket) {
var text = document.querySelector('#name');
socket.emit('newRemote', 'new remote connected');
console.log('emitted welcome');
socket.on('newScreen', function (data) {
console.log(data);
});
});
}
screen.js
var socket = null;
document.addEventListener("DOMContentLoaded", function(event) {
//some stuff
connectToServer();
});
function connectToServer(){
socket = io.connect('http://localhost:8080');
socket.on('connection', function (socket) {
var text = document.querySelector('#name');
socket.emit('newScreen', { name: name });
socket.on('newRemote', function (data) {
console.log(data);
});
});
};
when starting with node index.js i get
listening on *:8080
and when loading screen or remote.html i get
debug - client authorized
info - handshake authorized MwtGFRCZamcyKkUpK5_W
as I see it: somehow a connection is established, but:
no messages are sent / received on both ends
no logs are printed to the console for the connection events
any idea why nothing is happening?
It appears that you have mixed server-side code into your client. The 'connection' event is an event that needs to be listened to on the server, not your client files. Additionally, you cannot directly call client-side functions from your server-side code.
The below code does not work:
server.listen(8080, function(){
// setup image gallery and stuff...
connectToServer();
});
To achieve the above you will need to put the following code on your server:
server.listen(8080, function(){
socket.on('connection', function (socket) {
// setup image gallery and stuff...
socket.emit('connectToServer', myPassedParameters);
});
});
And the following listener for that event on the client:
socket.on('connectToServer', function (myPassedParameters) {
var text = document.querySelector('#name');
// stuff for client side here
});
});
In addition to the above, you cannot do calls from one client file to another client file using socket.io. You would have to do a call to the server first and then call a function on the other file once it has been loaded for the user.

Categories