I have a simple setup where I have some draggable divs and I want to use sockets.io to update the position between clients.
On my client (index.html) I have :
// find the elements
var elements = document.getElementsByClassName('ball'),
labelsX = document.getElementsByClassName('coords-x'),
labelsY = document.getElementsByClassName('coords-y');
// loop over the 3 items...
for (var n = elements.length; n--;) {
// ... augment our default options with individual `onDrag` handlers
var opts = {
onDrag: onDragFactory(n),
setCursor: true
};
// ... and initialize drag for each
window.d = new Draggable(elements[n], opts);
console.log('ddd');
}
// bind `n` to its value at iteration time
function onDragFactory (n) {
return function (element, x, y) {
//This doesnt seem to work
console.log(elements[n].style.top);
socket.emit('positionx', elements[n].style.top);
socket.on('positionx', function(positionx){
elements[n].style.top= positionx.value();
});
}
}
My server is then :
var express = require('express');
var path = require('path');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var publicPath = path.resolve(__dirname, 'public');
app.use(express.static(publicPath));
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
//Server Side Listen for an event from the client
io.on('connection', function(socket){
socket.on('positionx', function(positionx){
console.log('recieving');
console.log(positionx);
io.emit('positionx', positionx);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
The server however doesn't seem to receive any information. Is there something I'm doing wrong? Any help would be much appreciated!
In your client you need to define socket.
var socket = io();
Also, make sure you are including socket.io-x.x.x.js prior to calling socket.io in your javaScript. You are probably already doing this, but it's unclear without seeing more code.
Related
I have an array that is initialized when my user makes an input. I want that array to be passed to the nodeJS side of things rather than just stick around in the frontend. All the other variables that I am grabbing are named "net[object]" so I can grab them all in an array when necessary. The array I created only ever has one element being displayed in an input group at a time. If you need a better visual, go to "#nodes in hidden layer" for the neural net demo here: http://irisml.org/demos/
I am a complete noob when it comes to web development, so please be patient with me :)
//JS code creating array
numLayers.addEventListener('input', function(){
nodesArray.length = 0
num = numLayers.value;
nodes.innerHTML = '';
initialized = true;
for(var i = 1; i < num - 1; i++){
var node = document.createElement("option");
var textnode = document.createTextNode("Nodes in Hidden Layer " + i);
node.appendChild(textnode);
document.getElementById("nodes").appendChild(node);
nodesArray.push(1)
}
});
//Current NodeJS code
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.post('/', function(req, res){
console.log(req.body.net)
});
You can use "fetch" to send a post request to the backend.
//frontend
let nodesArray = [1,2,3];
let body = JSON.stringify({net:nodesArray});
fetch("/",
{method:"post",
body:body,
headers: {
'Content-Type': 'application/json'
}});
Your backend needs to listen on a port
//backend
var express = require('express');
var app = new express();
app.use(express.json())
app.listen(3000, console.error); //listen on port http://localhost:3000
app.use('/static', express.static(__dirname + '/static')); //OPTIONAL host static/index.html
app.post('/', function(req, res){
console.log(req.body.net, 'net');
res.send("RESPONSE");
});
I'm trying to do my best to explain what I'm trying to do, please let me know if something wasn't understandable.
I have a file called www where I'm setting up my socket like that
var server = http.createServer(app);
var io = require('socket.io')(server);
require('../store.js')(io);
I'm sending the io data to another file to use it properly. To capture the io I'm using.
module.exports = function (io){
}
What I'm trying to do is how could I use the io outside from the module.exports in the store.js file? I've tried to create a variable and then use it, but that doesn't seem to work.
Example how I've tried it.
var ioData;
ioData.on('connection', function(socket) {
//Doesn't work
});
module.exports = function(io){
ioData = io;
}
you can do this
store.js
const store = {
io: {},
setIo(io) {
store.io = io;
},
setHandlers() {
store.io.on('connection', function(socket) {
// do something with connected socket
});
}
};
module.exports = store;
www
var server = http.createServer(app);
var store = require('../store');
var io = require('socket.io')(server);
store.setIo(io);
store.setHandlers(io);
You need to create a add the connection event handler into the module export function, since when you change ioData, it doesn't re-add the handler.
var ioData;
module.exports = function(io){
ioData = io;
ioData.on('connection', function(socket) {
//Doesn't work
});
}
I have this code working for receiving data from my Arduino but I will like to send data back to my Arduino and get a response on my client page. I added a listening function but I keep getting io.on is not a function when I send data from my client page.
test.js
io.listen(app.listen(3000)).on('connection', function (client) {
// store client into array
clients.push(client);
// on disconnect
client.on('disconnect', function() {
// remove client from array
clients.splice(clients.indexOf(client), 1);
});
// I added this to listen for event from my chart.JS
io.on('connection', function(socket){
socket.on('LED on', function (data) {
console.log(data);
});
socket.on('LED off', function (data) {
console.log(data);
});
});
});
Your value of io is not what it should be.
The usual way of doing things is like this:
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(80);
io.on('connect', ...);
But I'm guessing that your value of io is something like this:
var io = require('socket.io');
That's not the same thing. That's the module handle. But, when you do it this way:
var io = require('socket.io')(app);
Then, io is a socket.io instance. You can bind listeners to an instance, not to the module handle.
In every single socket.io server-side example on this doc page, they use one of these forms:
var io = require('socket.io')(app);
var io = require('socket.io')(port);
var io = require('socket.io')(server);
with this:
io.on('connection', ....);
Nowhere do they do:
var io = require('socket.io`);
io.listen(server);
io.on('connection', ....);
That's just the wrong value for io.
Long story, shortened, you need to fix what you assign to io to be consistent with the docs. It's the return value from require('socket.io')(app); that gives you a socket.io instance object that you can then set up event handlers on.
if you are using express
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
let APP_PORT=3000;
server.listen(APP_PORT,()=>{
console.log(`SERVER RUNNING ON PORT : ${APP_PORT}`);
});
io.on('connection', (socket) => {
/* SOCKET - CORE EVENTS */
socket.on('connect', (message) => {
console.log("connected: " + message+"socket_id:"+socket.id);
});
socket.on('disconnect',(data)=>{
console.log('user disconnected:' + socket.id);
});
socket.on('error', function (err){
console.log('received error from client:', socket.id,' Error :',err);
});
});
I am using socket.io to create an interactive graph app. on the server side have a graph variable. When the user loads the page a test event is sent to the server, which sets up the variable and returns it to the users. I have a second event for node dragging, but when i try to drag the node the server says that the graph's nodes and link variables are undefined.
var express = require('express'),
app = express(),
http = require('http'),
socketIo = require('socket.io');
var server = http.createServer(app),
io = socketIo.listen(server);
var graph = {nodes : [], links : []}
server.listen(8080, function(){
console.log('server is listening on localhost:8080');
});
app.use(express.static(__dirname + '/'));
io.on('connect', function(socket){
// dump some test data
socket.on('test', function(){
// this just creates a few nodes in an array
var data = { ... }
graph = data;
io.emit('test', graph);
});
socket.on('eventNodeDragStart', function(index){
console.log('event node drag start: ' + index);
// undefiend, the graph.nodes is empty here
console.log(graph.nodes[index] + "\n\n");
// cannot read property of undefined
// also missing error handler on 'socket'
if(graph.nodes[index].locked) return;
graph.nodes[index].locked = true;
io.emit('eventNodeDragStart', index);
});
});
Solved the problem by replacing this line:
io.on('connect', function(socket){
with this:
io.sockets.on('connect', function(socket){
Not sure why it works, but it does.
I'm using node with express and socket.io to create a game server. I've put the game server in a extra module.
I have the problem that I can't access the game server object within the io event.
How do I solve this problem or should I structure my project differently?
// gameServer.js
'use strict'
var io = require('socket.io');
var socketioJwt = require('socketio-jwt');
var config = require('../config.js');
class GameServer {
constructor(http) {
this.io = new io(http);
this.connectedUsers = [];
this.initSocket();
}
initSocket() {
console.log('users', this.connectedUsers);
this.io.on('connection', this.onConnection);
}
onConnection(socket) {
console.log('users', this.connectedUsers); // undefined
}
}
I initialize the server like that:
'use strict'
var express = require('express');
var app = express();
var http = require('http').Server(app);
// init game server
var gameServerApp = new GameServer(http);
http.listen(3000, function() {
console.log('listening on *:3000');
});
I assume this is a common question but I can't figure out how to solve it.
You can bind this to this.onConnection
initSocket() {
console.log('users', this.connectedUsers);
this.io.on('connection', this.onConnection.bind(this));
}