Socket.io client doesn't receive message from Server - javascript

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/

Related

Heroku Sockets Javascript

I have the following example using Node.js for the server that sends data via Socket.io to a Javascript file. All works well locally, but when I uploaded to Heroku, it does not. I have tried a lot of tips I found online, but I am always stuck and can't get it through. At the moment, I don't get errors, but I also can't see the values coming through.
Here is the code I use at the moment:
var express = require('express');
var socket = require('socket.io');
//store the express functions to var app
var app = express();
//Create a server on localhost:3000
var server = app.listen(process.env.PORT || 3000);
//var server = app.listen((process.env.PORT || 3000, function(){
//console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
//});
//host content as static on public
app.use(express.static('public'));
console.log("Node is running on port 3000...");
//assign the server to the socket
var io = socket(server);
//dealing with server events / connection
io.sockets.on('connection', newConnection); //callback
//function that serves the new connection
function newConnection(socket){
console.log('New connection: ' + socket.id);
socket.on('incomingDataToServer', emitFunction);
function emitFunction(data){
//setInterval(() => socket.broadcast.emit('ServerToClient', new Date().toTimeString()), 1000);
let randNum;
setInterval(function(){
//get a random value, and assign it a new variable
randNum = getRandomInt(0, 100);
}, 1000);
socket.broadcast.emit('ServerToClient', randNum);
//following line refers to sending data to all
//io.sockets.emit('mouse', data);
console.log(randNum);
}
}
And the Javascript here:
let socket;
socket = io();
socket.on('ServerToClient', socketEvents);
function socketEvents(data){
incomingData = data;
console.log(data);
}
Any help is appreciated.
Thanks
Write app.use before the app listen
and modify app.listen as below and check heroku logs for console message.
app.use(express.static('public'));
var server = app.listen(port, function() {
console.log('Server running on ' + port + '.');
});
if It still not work let me know.

Connect to a third party socket.io server

I'm creating a socket.io server like so:
var http = require('http');
var io = require('socket.io');
var port = 8080;
var server = http.createServer(function(req, res){
res.writeHead(200,{ 'Content-Type': 'text/html' });
res.end('<h1>Hello Socket Lover!</h1>');
});
server.listen(port);
// Create a Socket.IO instance, passing it our server
var socket = io.listen(server);
// Add a connect listener
socket.on('connection', function(client){
console.log('Connection to client established');
// Success! Now listen to messages to be received
client.on('message',function(event){
console.log('Received message from client!',event);
});
client.on('disconnect',function(){
clearInterval(interval);
console.log('Server has disconnected');
});
});
console.log('Server running at http://127.0.0.1:' + port + '/');
The server works fine and starts, however when I'm connecting through js like this:
$(function(){
var socket = io();
socket.connect('http://localhost:8080');
});
It's not connecting and I'm getting this in dev tools console.
polling-xhr.js:264 GET http://file/socket.io/?EIO=3&transport=polling&t=Lz53lhL net::ERR_NAME_NOT_RESOLVED
I'm loading socket.io.js like this:
<script src="http://127.0.0.1:8080/socket.io/socket.io.js"></script>
Change
$(function(){
var socket = io();
socket.connect('http://localhost:8080');
});
to
$(function(){
var socket = io('http://localhost:8080');
});
You need to pass the url of your socket server to the io function

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

Socket.IO and Express

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

Categories