Socket.io - nothing gets written to client - javascript

I've been trying to start with Socket.io and the initial example on their site doesn't work for me. This is what I'm trying to do:
my Server.js
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(80);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
my index.html:
<script src="/socket.io/socket.io.js"></script>
<script>
console.log('inside');
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
console.log(socket);
</script>
There are couple of questions on stackoverflow, but nothing that I can co-relate,I'm not getting a 404 error.
My project structure is like this:
ProjectName:
Node Modules
Server.js
index.html
I really don't know what's happening, Please help.Thanks.

Related

Socket.IO emit not sending

I am currently building a game using Socket.IO and Javascript. I originally wanted to make a real-time multiplayer game, however, I ran into a problem really quick. I eventually gave up and moved to a turn-based game but the problem still didn't go away.
The problem is that the server (app.js) is not getting emits from the client (game.js). I've tried recreating the project, console.log, and search google to no avail.
App.js
require('./Database');
var express = require('express');
var app = express();
var serv = require('http').Server(app);
app.get('/', function(req, res) {
res.sendFile(__dirname + '/client/index.html');
});
app.use('/client', express.static(__dirname + '/client'));
serv.listen(process.env.PORT || 2000);
console.log("Server started.");
var SOCKET_LIST = {};
var io = require('socket.io')(serv, {});
io.sockets.on('connection', function(socket) {
socket.id = Math.random();
SOCKET_LIST[socket.id] = socket;
socket.on('signIn', function(data) { // {username,password}
Database.isValidPassword(data, function(res) {
if (!res)
return socket.emit('signInResponse', { success: false });
Database.getPlayerProgress(data.username, function (progress) {
socket.emit('signInResponse', {
success: true, username: data.username,
progress: progress
});
})
});
});
socket.on('signUp', function(data) {
Database.isUsernameTaken(data, function(res) {
if (res) {
socket.emit('signUpResponse', { success: false });
} else {
Database.addUser(data, function() {
socket.emit('signUpResponse', { success: true });
});
}
});
});
socket.on('disconnect', function() {
delete SOCKET_LIST[socket.id];
});
socket.on("findMatch", function(data) {
console.log('test'); // ******* Not working ********
});
});
Game.js
var socket = io("127.0.0.1:2000");
function findMatch(data) {
socket.emit("findMatch", { socket: socket });
}
FindMatch() is called from the lobby "Find Match" Button. It is hooked up to an onclick listener.
Thank you. I would appreciate any help.
Edit: The connection, sign In, register, and disconnect emits DO work only custom ones I add later (findMatch for example) don't work

Socket.io - Connect from client to server via https

I have created a socket.io chat application on my virtual server (Ubuntu), which runs as an systemd service and which is active running.
My server.js is located in:
/var/www/vhosts/mywebpage.de/w1.mywebpage.de/chat/
The server.js looks like this:
const io = require('socket.io')(3055);
io.on('connection', function(socket) {
// When the client emits 'addUser', this listens and executes
socket.on('addUser', function(username, room) {
...
});
// When the client emits 'sendMessage', this listens and executes
socket.on('sendMessage', function(msg) {
...
});
// Disconnect the user
socket.on('disconnectUser', function(username, room) {
...
});
});
In my website (https) I try to connect as follow:
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<script type="text/javascript">
var loSocket;
$(document).ready(function() {
if(typeof(loSocket) == 'undefined') {
loSocket = io('https://w1.mywebpage.de:3055', {
reconnectionAttempts: 5,
forceNew: true
});
}
});
</script>
But I can't get a valid connection.
The developer tools say this:
(failed) ERR_CONNECTION_CLOSED with initiator polling-xhr.js:264.
What could be the error ?
From what I have done in the past I would create a https server which serves the SSL cert and create the socket server using the https server you created, this will allow you to connect via https and you will need to enable secure on socketio (use this question as a ref)
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(80);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Use this code as ref on how to create a socketio server using http
You can find this code on the socket.io docs
NOTE: You will need to you https not http like shown in the example

kill() function is not recognized for child_process

Using node js I'm calling external script in MATLAB and Python
That is working well using terminal commands to run the scripts using those application ('start')
But when I'm trying to close them using kill() ('stop') I get an error:
TypeError: exec.kill is not a function
I'm using MAC OS and this is my code:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs');
var path = require('path');
const exec = require('child_process').exec;
var cmd1 =
'/Applications/MATLAB_R2016b.app/bin/matlab -nojvm < /Users/dorsimon/Desktop/liftrack/Testing_Classifier.m';
var cmd2 = 'python /Users/dorsimon/Desktop/liftrack/arduino_sampling_for_workout.py';
app.get('/', function(req, res) {
res.sendfile('index.html');
});
//Whenever someone connects this gets executed
io.on('connection', function(socket) {
console.log('A user connected');
fs.watch('/Users/dorsimon/Desktop/liftrack/result/', function(event, test) {
console.log('event is: ' + event);
fs.readFile('/Users/dorsimon/Desktop/liftrack/result/results.csv', 'utf-8', function read(
err,
data
) {
if (err) {
console.log('err');
throw err;
}
console.log(data);
socket.send(data);
});
});
fs.watch('/Users/dorsimon/Desktop/liftrack/go', function(event, test) {
console.log('event is: ' + event);
fs.readFile('/Users/dorsimon/Desktop/liftrack/go/go.csv', 'utf-8', function read(err, data) {
if (err) {
console.log('err');
throw err;
}
console.log(data);
socket.send(data);
});
});
//Whenever someone disconnects this piece of code executed
socket.on('disconnect', function() {
console.log('A user disconnected');
});
socket.on('start', function() {
exec(cmd1, function(error, stdout, stderr) {
// command output is in stdout
});
exec(cmd2, function(error, stdout, stderr) {
// command output is in stdout
});
});
socket.on('stop', function() {
exec.kill();
});
});
http.listen(3000, function() {
console.log('listening on *:3000');
});
How can I kill those child_process that I started?
Thanks
Dor
You need to store the return value of exec and call kill on that. You can store those values as properties on socket for convenience:
socket.on('start', function() {
socket.child1 = exec(cmd1, function(error, stdout, stderr) {
// command output is in stdout
});
socket.child2 = exec(cmd2, function(error, stdout, stderr) {
// command output is in stdout
});
});
socket.on('stop', function() {
socket.child1.kill();
socket.child2.kill();
});
FWIW, you probably have to do the same with the return values of fs.watch(), and call close() on them when the socket gets closed, otherwise you'll probably run into issues after your server has been running for a while (it creates two watchers for each socket.io connection, but doesn't remove them, so they'll linger).

Node.js socket.io webserver provide other file than index.html

I started learn socket.io and use this example of chat.
When I go to ip:8080/public/index.html, I also need access to other files, for example other JS scripts, which will be used on client side in the browser. But when I put script load like this:
<script src="/js/phaser.js" type="text/javascript"></script>
the web server does not return it, and I need it on this handler code.
I have this code:
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(8080);
function handler (req, res) {
console.log(req.headers.referer);
fs.readFile(__dirname + '/public/index.html', // <--- I need here put filename which client wants it, but when I console.log to req it return HUGE data, I not found anythink usefull
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
socket.broadcast.emit('new message', data);
console.log(data);
});
socket.on('msg', function(data){
console.log(data);
})
});
You can use Express static for serving static files like your *.js files.

Can't send message to all sockets (socket.io)

Heya I'm trying to build a small chat client to learn how websockets work in order to make a game in canvas. It works great with sending sockets but they are only sending it to the the one who wrote it.
I guess I've missed something small, but I can't understand why it won't work.
Server side code
var app = require('express')()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
server.listen(3000);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
socket.on('user-message', function (data) {
console.log(data);
sendMessage(data.message);
});
});
var sendMessage = function(message) {
io.sockets.emit('server-message', {message: message});
}
Client side code
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('server-message', function (data) {
var history = $('#chatbox').val();
$('#chatbox').val(history + "\n" + data.message)
});
$("#write").keyup(function(event){
if(event.keyCode == 13){
socket.emit('user-message', {message: $(this).val()});
$(this).val('');
}
});
</script>
You can use socket.broadcast.emit to send a message to all other sockets.
io.sockets.on('connection', function (socket) {
socket.on('user-message', function (data) {
console.log(data);
sendMessage.call(socket, data.message);
});
});
var sendMessage = function(message) {
this.emit('server-message', {message: message});
this.broadcast.emit('server-message', {message: message});
}

Categories

Resources