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!');
});
Related
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>
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
})
This is my 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);
const port = 3000 || process.env.PORT;
app.listen(port, () => {
console.log(`server running on port ${port}`);
});
io.on('connection', socket => {
console.log(socket);
});
This is my Client Side:
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
</script>
</body>
</html>
I re-installed all the modules correctly, but it did not help.
The problem is that you're creating two web servers, attaching socket.io to one of them, but only starting the other one.
Both of these lines of code create a new web server:
const server = http.createServer(app);
app.listen(port, ...);
But, only the second one actually gets started and that's NOT the one you bound socket.io to. So, the server you bound socket.io to is never started, therefore none of the client-side stuff that is supposed to talk to your socket.io server will work properlly.
To fix it, change your server code to this:
const path = require('path');
const express = require('express');
const socketio = require('socket.io');
const app = express();
const port = 3000 || process.env.PORT;
const server = app.listen(port, () => {
console.log(`server running on port ${port}`);
});
const io = socketio(server);
io.on('connection', socket => {
console.log(socket);
});
Now, you will only be creating one web server, starting that server and binding socket.io to that one server.
I am trying to use the socket-anti-spam module (https://github.com/michaeldegroot/socket-anti-spam) in my web application. However, when I try using it, I get the following error:
Error: listen EADDRINUSE :::3000
Below is my code:
var express = require("express");
var socket = require("socket.io");
var socketListen = socket.listen(3000);
var bodyParser = require('body-parser');
var cors = require('cors');
var SocketAntiSpam = require("socket-anti-spam");
require('dotenv').config({ path: 'variable.env' });
// Initialize Node.JS application
var app = express();
var server = app.listen(process.env.PORT || 3000);
app.use(express.static("public", {
dotfiles: 'allow'
}));
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const socketAntiSpam = new SocketAntiSpam({
banTime: 30, // Ban time in minutes
kickThreshold: 2, // User gets kicked after this many spam score
kickTimesBeforeBan: 1, // User gets banned after this many kicks
banning: true, // Uses temp IP banning after kickTimesBeforeBan
io: socketListen, // Bind the socket.io variable
});
You are trying to listen on the same port (3000) twice that’s why you are getting “Address In Use” error.
Try something like:
const SocketAntiSpam = require('socket-anti-spam')
const app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
const listen = server.listen(3000);
const socketAntiSpam = new SocketAntiSpam({
banTime: 30,
kickThreshold: 2,
kickTimesBeforeBan: 1,
banning: true,
io: io,
})
io.on('connection', function(socket){
console.log('a user connected');
socket.on('spam', (data) => {
console.log(data);
})
});
app.get('/hello', (request, response) => {
response.send('ok');
});
I was following the second example here:
https://github.com/socketio/socket.io-client
and trying to connect to a website that uses websockets, using socket.io-client.js in node.
My code is as follows:
var socket = require('socket.io-client')('ws://ws.website.com/socket.io/?EIO=3&transport=websocket');
socket.on('connect', function() {
console.log("Successfully connected!");
});
Unfortunately, nothing gets logged.
I also tried:
var socket = require('socket.io-client')('http://website.com/');
socket.on('connect', function() {
console.log("Successfully connected!");
});
but nothing.
Please tell me what I'm doing wrong. Thank you!
Although the code posted above should work another way to connect to a socket.io server is to call the connect() method on the client.
Socket.io Client
const io = require('socket.io-client');
const socket = io.connect('http://website.com');
socket.on('connect', () => {
console.log('Successfully connected!');
});
Socket.io Server w/ Express
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const port = process.env.PORT || 1337;
server.listen(port, () => {
console.log(`Listening on ${port}`);
});
io.on('connection', (socket) => {
// add handlers for socket events
});
Edit
Added Socket.io server code example.