Socket.IO and Express - javascript

Here is my NodeJS server:
var express = require('express');
var app = express();
var port = process.env.PORT || 1337;
var server = app.listen(port);
var io = require('socket.io').listen(server);
io.sockets.on('connection', function(socket){
console.log('A user connected to the chat!');
socket.on('chat message', function(msg){
console.log('message: ' + msg);
});
});
And here is my client:
var socket = io();
socket.connect('http://server:1337', { autoConnect: true});
socket.on('connect',function() {
socket.emit('chat message', "TEST");
});
And on my client side I get the following error in the console:
Cannot GET /socket.io/?EIO=3&transport=polling&t=LOIMkAR

You only need to use var socket = io.connect(), it will try to connect to the server automatically.
Unless you want to connect to a custom IP, which don't make much sense. io.connect() will do what you want to do.
After that you will use socket.emit for emitting events and socket.on for listening to events.

I've got this working with this setup similar to socket.io docs
var express = require('express');
var app = express();
var port = process.env.PORT || 1337;
var server = require('http').Server(app);
var io = require('socket.io')(server);

Related

Socket.io client doesn't receive message from Server

I'm using Socket.IO for websockets and I want clients receive a welcome message in console from server when they connect but it's not working:
Server:
var fs = require('fs');
var https = require('https');
var express = require('express');
var app = express();
var options = {
key:
fs.readFileSync('/myfolder/mykey.pem'),
cert:
fs.readFileSync('/myfolder/mychain.pem')
};
var serverPort = 3080;
var server = https.createServer(options,app);
var io = require('socket.io')(server);
app.get('/',function(req,res){
res.sendFile(__dirname+'/index.html');
});
server.listen(serverPort, function(){
console.log('Server is working');
//console.log(__dirname);
});
io.on('connection', function(socket){
console.log("Connected!");
socket.broadcast.emit("Welcome","Good day sunshine!");
});
Client:
<script src="https://localhost:3080/socket.io/socket.io.js"></script>
<script>
var URL_SERVER = 'https://localhost:3080';
var socket = io.connect(URL_SERVER);
socket.on("Welcome", function(data){
console.log(data);
});
</script>
I'm getting message console in server side but not the server answer in the console client.
How can I fix it?
To broadcast, simply add a broadcast flag to emit and send method
calls. Broadcasting means sending a message to everyone else except
for the socket that starts it.
Reference : https://socket.io/docs/

Node.js socket.io returning multiple values for a single event

I'm trying to build a simple app using Node, Express (^4.15.3), and socket.io (^2.0.3). I'm building a simple chat app, however each time I add a new message, I get an additional response each time.
For example, if the first message was "Hello", I would be returned:
Hello
If I then add a subsequent message of "Is anyone there?", I get back:
Is anyone there?
Is anyone there?
And so on...each time I get an additional response back.
Here's my code - it feels like it's something really obvious and I may have been staring at it too long...
//app.js
var express = require("express");
var bodyParser = require("body-parser");
var expressValidator = require('express-validator');
var session = require('express-session');
var passport = require("passport");
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
app.use(express.static("public"));
app.set("view engine", "ejs");
server.listen(process.env.PORT || 3000, process.env.IP, function(){
console.log("Server starting...");
});
app.get('/testsocket', function(req, res){
res.render('sockets/test');
});
io.sockets.on('connection', function(socket){
console.log('Connected')
socket.on('send message', function(data){
console.log('Got the message...');
io.sockets.emit('new message', data)
});
});
And then client side
//client side
$(function() {
var socket = io.connect();
var $messageForm = $('#send-message');
var $messageBox = $('#message');
var $chat = $('#chat');
$messageForm.submit(function(e){
e.preventDefault();
socket.emit('send message', $messageBox.val());
$messageBox.val('');
socket.on('new message', function(data){
$chat.append(data + "<br>");
});
});
});
I think the problem is that you're registering the listener for new message inside your submit function. So each time you submit the form you register a new listener, in addition to any previous listeners. Try putting the socket.on('new message', ... section outside the submit handler.

Configuring socket.io for node.js application

I have a few questions about configuring socket.io for my node.js application.
When requiring var socket = require('socket.io')( /* HERE */ ), do I need to input the port my server listens where the /* HERE */ is at?
Right below the above line, I have another require function, for a .js file that contains a few constants and a function (see below). When I try to refer to 'socket' in that file it says it's undefined. But since this line is below the require line for the socket.io middleware seen above, why does it say 'undefined'?
const numbers = '1234'
function asd(req,res,next) {
socket.emit('a')
}
module.exports = {
asd
}
For configuring client-side socket.io, I added this line:
var socket = io.connect('https://mydomain')
Do I need to say 'mydomain:port' or is 'mydomain' enough?
This is how you use socket.io
var http = require('http');
var express = require('express');
var path = require('path');
var app = http.createServer();
var io = require('socket.io')(app);
var port = 8081;
io.on('connection', function(socket){
socket.on('event1', function (data) {
console.log(data);
socket.emit('event2', { msg: 'delivered' });
});
});
app.listen(port);
Answer to your second question
Yes, you will need to specify the port you are using
<script src="socket.io.js"></script>
<script>
var socket = new io.Socket();
socket.connect('https://mydomain:8081')
socket.on('your_event',function() {
console.log('your_event receivid from the server');
});
</script>
Here socket will connect to port 8081
This is a simple server side code
var http = require('http');
var io = require('socket.io');
var port = 8081;
// Start the server at port 8081
var server = http.createServer();
server.listen(port);
var socket = io.listen(server);
// example listener
socket.on('event_2', function(client){
console.log('event_2 received');
});
// example emitter
socket.emit('event_1', { hello: 'world' });

io.on is not a function

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);
});
});

scoket.io is not found when listening to different port than server

I have set up a server in node.js using socket.io and epxress.
When I set it up as shown below, it works like charm (now it's listening on 8080).
var express = require("express");
var http = require("http");
var io = require("socket.io");
var app = express();
var server = http.createServer(app).listen(port, host);
var scoketIO = io.listen(server);
But I need it to listen to different port, and if I try eg. 8000
var app = express();
var server = http.createServer(app).listen(port, host);
var scoketIO = io.listen(8000);
I get the following error:
GET http://10.0.33.34:8080/socket.io/socket.io.js 404 (Not Found). Can anybody please help me?
var express = require("express");
var http = require("http");
var io = require("socket.io");
var app = express();
var port = 8000;
var server = http.createServer(app).listen(port, host);
var scoketIO = io.listen(server);
Above code is not tested but most likely it will not fail. Pass port value to listen method of http.createServer(app).
var express = require('express')
http = require('http');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(8000);
//Code needs to be in this order
and check in the script that the port is 8000
<script src=""></script>
Do you include the script in you html ?
Maybe change the include to the port 8000.
<script src="http://10.0.33.34:8000/socket.io/"></script>

Categories