Need your help/guidance/suggestion for our scenario.
Issue: I am having some trouble connecting socket io client to socket io server. The error I got after running this code is connection time out.
My server code is :
const port = process.env.PORT || 4004;
const http = require('http');
const socket = require('socket.io');
const app = express();
const httpServer = http.createServer(app);
const io = new socket.Server(httpServer);
io.on('connection', (socket) => {
console.log("Socket connected");
});
httpServer.listen(port, () => {
console.log("Listening on port ",port);
});
My client code is:
<script src = "socket.io.min.js"> </script>
<script>
var socket = io.connect(`wss://${document.location.hostname}:${port}`);
console.log(socket);
socket.on('done', (data) => {
console.log(data);
});
</script>
Your server code does not start in my node installation.
I correct your server code with this below and seems to work
fine on my node installation. You forgot to link express library
const port = process.env.PORT || 4004;
const http = require('http');
const socket = require('socket.io');
const express = require('express');
const app = express();
const httpServer = http.createServer(app);
const io = new socket.listen(httpServer);
io.on('connection', (socket) => {
console.log("Socket connected");
});
httpServer.listen(port, () => {
console.log("Listening on port ", port);
});
You can do with this script. This is my personal working script for socket IO chat app.
Backend Server
require("dotenv").config();
const port = process.env.SOCKET_PORT || 3000;
const main_server_url = process.env.SERVER_URL;
var express = require("express");
var app = express();
var server = app.listen(port);
var connectionOptions = {
"force new connection": true,
"reconnection": true,
"reconnectionDelay": 2000, //starts with 2 secs delay, then 4, 6, 8, until 60 where it stays forever until it reconnects
"reconnectionDelayMax": 60000, //1 minute maximum delay between connections
"reconnectionAttempts": "Infinity", //to prevent dead clients, having the user to having to manually reconnect after a server restart.
"timeout": 10000, //before connect_error and connect_timeout are emitted.
"transports": ["websocket"] //forces the transport to be only websocket. Server needs to be setup as well/
}
var io = require("socket.io").listen(server, connectionOptions);
var axios = require("axios");
var users = [];
var connections = [];
console.log("Server connected done");
io.sockets.on("connection", function (socket) {
var server_url = main_server_url;
console.log(server_url);
console.log(people);
connections.push(socket);
console.log("Connected : total connections are " + connections.length);
// rest of events of socket
});
Front End JS for load IO for client
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
<script type="text/javascript">
var base_url = YOUR_BASE_URL;
var port = YOUR_SOCKET_PORT;
var socket_port_url = base_url + ":" + port;
var socket = io(socket_port_url);
socket.on('done', (data) => {
console.log(data);
});
</script>
Related
Why does my socket.io webapplication keeps loading, i've implemented auth with certifications, but when i try to access localhost, it keeps loading. ive tried follow this doc, but dosent help:https://socket.io/docs/v3/client-initialization/
i dont get any error.
server.s
'use strict';
// Setup basic express server
var express = require('express');
var app = express();
var port = process.env.PORT || 4000;
var crypto = require('crypto');
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('./data/db.sqlite');
const bcrypt = require('bcrypt');
const tls = require('tls');
var validator = require('validator');
// Routing
app.use(express.static(__dirname + '/public'));
app.use(express.json());
// Chatroom
// usernames which are currently connected to the chat
var usernames = {};
var numUsers = 0;
const fs = require("fs");
const server = require("https").createServer({
cert: fs.readFileSync("./server-cert.pem"),
key: fs.readFileSync("./server-key.pem")
});
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
const io = require("socket.io")(server);
io.on('connection', function (socket) {
console.log("works")
}
client.js
const fs = require("fs");
const socket = require("socket.io-client")(4000, {
ca: fs.readFileSync("./server-cert.pem")
});
socket.on("connect_error", (err) => {
console.log(`connect_error due to ${err.message}`);
});
I'm new to WS and Heroku and all that... so i have this code
//this sets up client-side sockets i guess
import {io} from 'socket.io-client';
const options = {
"force new connection": true,
reconnectionAttempts: "Infinity",
timeout : 10000,
transports : ["websocket"]
}
const socket = io('/', options)
export default socket;
and for the server side
const path = require('path');
const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
const {version, validate} = require('uuid');
const ACTIONS = require('./src/socket/actions');
const PORT = process.env.PORT || 3001;
///more code
When deployed to heroku this results in this app https://lit-atoll-99067.herokuapp.com/ and the chrome console says :
WebSocket connection to
'wss://lit-atoll-99067.herokuapp.com/socket.io/?EIO=4&transport=websocket'
failed: WebSocket is closed before the connection is established.
So i ran out of ideas. but i guess this has to be about port or something... dunno really. Any ideas are welcome!
I think you need to pass the full URL at the client-side but you only passed the "/" only example:-
import {io} from 'socket.io-client';
const options = {
"force new connection": true,
reconnectionAttempts: "Infinity",
timeout : 10000,
transports : ["websocket"]
}
// here need to pass the full url
const socket = io('https://example.com/', options)
export default socket;
And for the server side try this
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
io.on('connection', (socket) => {
console.log('a user connected');
});
server.listen(3000, () => {
console.log('listening on *:3000');
});
My code isn't logging any messages in my console, I need the code to log a message when I run my server
Server side
const path = require('path');
const http = require("http");
const express = require("express");
const socketio = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
//set static folder
app.use(express.static(path.join(__dirname, 'public')));
//Run when client connects
io.on('connection', function(socket){
//welcome current user
socket.emit("message", 'Welcome to ChatApp');
//Broadcast when a user connects
socket.broadcast.emit('message', 'A user has join the chat');
//Runs when client disconnect
socket.on('disconnect', ()=>{
io.emit('message', 'A user has left the chat')
})
});
const PORT = 3000 || process.env.PORT;
server.listen(PORT, () => console.log('Server running on port ${PORT}'));
Client side
const socket = io();
io.sockets.on("message", message =>{
console.log("message")
})
its like as if the client side isnt functioning
The problem is in your client code.
You set up a variable named socket but then attempt to set a handler on io.sockets
Change:
const socket = io();
io.sockets.on("message", message =>{
console.log("message")
})
To:
const socket = io();
socket.on("message", message =>{
console.log("message")
})
Initiate the socket by providing required parameters like URL and the optional parameters if required
socket = io('<SERVER_URL_HERE>', {
reconnection: true, // optional
reconnectionDelay: 1000, // optional
reconnectionDelayMax : 25000, // optional
reconnectionAttempts: Infinity, // optional
autoConnect: true, // optional
query:{isAgent,agentId,isCustomer,projectId} // optional
})
I am trying to send data from one node server to another node server. But when i host the one server on heroku i am not able to obtain a socket connection.
Hope anybody can help. Thanks in advance
server.js
var express = require('express');
var socketIO = require('socket.io');
var path = require('path');
var value = "default";
var PORT = process.env.PORT || 3000;
// var engines = require('consolidate');
// app.set('views', __dirname + '/views');
// app.engine('html', engines.mustache);
// app.set('view engine', 'html');
var app = express();
//var server = app.listen(PORT, () => console.log(`Listening on ${
PORT }`));
var server = require('http').createServer(app);
var io = socketIO(server);
io.on('connection', (socket) => {
console.log('+Client connected successfully+');
socket.on('data', function (data) {
console.log('data from pi' + data);
});
socket.on('disconnect', () => console.log('Client
disconnected'));
});
//console.log(PORT + 'actual listening to'+server.address().port);
server.listen(PORT);
client.js
var io = require('socket.io-client');
var socket = io.connect('https://herokuappname.herokuapp.com/', {
reconnect: true });
console.log('2');
// Add a connect listener
socket.on('connect', function (socket) {
console.log('Connected!');
});
I'm trying to connect to a nodejs server over a websocket connection but can't get anything to work.
My server.js looks like this:
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io', {
transports: ['websocket']
})(http);
var server_port = process.env.PORT || 8080
var server_ip_address = process.env.IP || '0.0.0.0'
app.listen(server_port, server_ip_address, function () {
console.log('listening on ' + server_ip_address + ":" + server_port);
});
My client.js (running on a raspberry pi also running nodejs) is:
var io = require('socket.io-client');
var socket = io.connect('http://<app-url>',
{
reconnect: true,
transports: ['websocket']
}
);
socket.on('connect', function(socket) {
console.log('Connected!');
});
I've also tried on openshift v2 (ports 8000 and 8443) and v3 and no luck there.
If anyone has done this recently please let me know how, thanks!
When debugging the client I get the message:
engine.io-client:socket socket close with reason: "transport error"
and on the server:
heroku[router]: at=error code=H13 desc="Connection closed without response"
It looks like a strange bug that happens sometimes, you should be able to get through by adding the path of your client library in the options like so :
var socket = io.connect('http://<app-url>:8080',
{
reconnect: true,
transports: ['websocket'],
path: "/lib/socket.io.js" //use the relevant path for your file
}
);
But you seem to be using the default options anyway, so you could just do :
var socket = io.connect();
Ok, it's working now. I modified the example in the heroku docs
I'm not quite sure why my server config doesn't work, but the following does work:
server.js
var express = require('express');
var socketIO = require('socket.io');
var path = require('path');
var PORT = process.env.PORT || 3000;
var app = express();
var server = app.listen(PORT, () => console.log(`Listening on ${ PORT }`));
var io = socketIO(server);
io.on('connection', (socket) => {
console.log('Client connected');
socket.on('disconnect', () => console.log('Client disconnected'));
});
client.js (xShirase was right in saying I needed the correct path here...)
var io = require('socket.io-client');
var socket = io.connect('https://<url>',
{reconnect: true, transports : ['websocket'], path: '/socket.io'});
socket.on('connect', function (socket) {
console.log('Connected!');
});