Socket.IO Client How to Connect? - javascript

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.

Related

Socket.io is not found in the client-side

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.

Why am I not able to access the express server from a different file?

I have set up an express server as follows (inside of server.js ) :
const app = express();
.........
.....
const PORT = process.env.PORT || 5000;
const server = app.listen(PORT, () =>
console.log(`Server started on port ${PORT}`)
);
module.exports = server;
Inside of another file socket.js:
const server = require("./server");
const socketio = require("socket.io");
const io = socketio(server);
io.on("connection", function (socket) {
console.log("A user just joined!");
socket.on("disconnect", () => {
console.log("A socket just left!");
});
});
For some reason I get an error in my console while trying to connect to the socketio on the client:
GET http://localhost:3000/socket.io/?EIO=3&transport=polling&t=N8-d7Q4 404 (Not Found)
The error does not occur if I execute everything in a single file (without exporting the server):
const PORT = process.env.PORT || 5000;
const server = app.listen(PORT, () =>
console.log(`Server started on port ${PORT}`)
);
const socketio = require("socket.io");
const io = socketio(server);
io.on("connection", function (socket) {
console.log("A user just joined!");
socket.on("disconnect", () => {
console.log("A socket just left!");
});
});
I don't understand what's wrong. Does module.exports not work with the express server or is this is a socketio issue ?
It appears you're not loading socket.js at all. When you had only the one file, you just did node app.js and that would work fine. But, if you do node app.js with your two files, then there's nothing to ever load socket.js at all. In fact, the way you have the two files laid out, you would have to do:
node socket.js
to initialize things. Then, socket.js does a require('./app.js') to get app.js loaded.
I was wondering if it's impossible to module.exports = server at all
Yes, you can freely export the server and you are exporting it.
Another way of doing things is to still have app.js be your main file that you load to start up your app and you load socket.js from there and pass it the server object so it can use it.
// app.js
const server = const server = app.listen(...);
// load socket.js and pass it our server
require('./socket.js')(server);
Then in socket.js:
// socket.js
const socketio = require("socket.io");
module.exports = function(server) {
const io = socketio(server);
// rest of your module code here
}

Socket io namespaces do not fire on("connection") event

I am using socket.io both (server API and client API) on Node.js as client and server. This is possible as specified in the docs). I am not using any particular frameworks except Express and followed the official guide for using socket.io with it.
On the server side I have:
const express = require("express");
const app = express();
const http = require("http");
server = http.Server(app);
const io = require("socket.io")(server) //server listens on "http://localhost:3001
io.on("connection", socket => {
console.log("server says: someone connected");
});
On the client side I have:
const io = require("socket.io-client")("http://localhost:3001");
io.on("connect", () => {
console.log("client says: connected");
});
Until here everything works fine... Now when adding namespaces nothing seem to work anylonger. I followed the official guide and ended up with the following:
On the server side I have:
const express = require("express");
const app = express();
const http = require("http");
server = http.Server(app);
const io = require("socket.io")(server) //server listens on "http://localhost:3001
const nsp = io.of('/my-namespace');
nsp.on("connection", socket => {
console.log("server says: someone connected");
});
On the client side I have:
const io = require("socket.io-client")("http://localhost:3001");
const socket = io('/my-namespace');
socket.on("connect", () => {
console.log("client says: connected");
});
But the after the introduction of namespaces nothing seems to work... What am I missing?!
Thanks I am completely lost

Socket.io connected always false

My socket.connected is always false, cannot emit or receive messages too.
app.js
var app = require('./config/server');
var http = require('http').Server(app);
var io = require("socket.io")(http);
http.listen(80, function(err)
{
console.log(err);
console.log('Server client instagram_clone_v01 online');
});
io.sockets.on('connection', function (socket)
{
console.log("new user connected");
});
server side
var sockets = io();
sockets.on('connection', function ()
{
console.log("connected");
sockets.emit("newPhoto");
});
client side
const socket = io.connect("http://localhost:80");
console.log(socket.connected);
socket.on('error', function()
{
console.log("Sorry, there seems to be an issue with the connection!");
});
socket.on('connect_error', function(err)
{
console.log("connect failed"+err);
});
socket.on('connection', function ()
{
console.log("connected");
socket.on('newPhoto',function()
{
load_posts();
});
});
None of the "on"s are received, not even "error". So how can i make it work, please?
I've checked Your code locally.
So issue was that You're checking: .on('connection',...) when it should be .on('connect', ...)
So try this fix:
socket.on('connect', function() {
console.log("Connected to WS server");
console.log(socket.connected);
load_posts();
});
socket.on('newPhoto', function(){
load_posts();
});
When I was building a basic socketio app using React frontend and Node Express backend, I came across a similar problem in v4. With the typical Node/React setup, your react app will live on port 3000 and your express server will live on port 5000, and according to the docs this results in you needing to set an open CORS policy to enable connections to the socketio server on port 5000.
Since Socket.IO v3, you need to explicitly enable Cross-Origin
Resource Sharing (CORS).
(docs)
I simply made sure my socketio definition was as such:
const app = express();
const httpServer = http.createServer(app);
const io = require("socket.io")(httpServer, {
cors: {
origin: "http://localhost:8080",
methods: ["GET", "POST"]
}
});
and I Was able to connect from a my react app inside of a useEffect. I was seeing all of the expected logs thereafter.
useEffect(() => {
socket = io('localhost:5000');
socket.on('connect', () => {
console.log('socket connected');
console.log(socket);
});
}, []);

Express nodejs socket.io with cordova

I'm trying to implement socket.io on my server. This server is an API (express nodejs).
The server side is simple, but for the client side I'm using phonegap/cordova.
I don't use a phone to test what I do, I use my browser (chrome).
Si this the server side :
var express = require('express'); // call express
var app = express(); // define our app using express
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket){
console.log('a user connected');
console.log(socket);
socket.on('disconnect', function () {
console.log('socket disconnected');
});
io.emit('text', 'wow. such event. very real time.');
});
for now, this is simple,
But for the client side I am completely confuse (cordova phonegap),
This is what I have :
index.html
<script type="text/javascript" src="http://cdn.socket.io/socket.io-1.0.3.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
socket.on('news', function (data) {
console.log('send')
socket.emit('my other event', { my: 'data' });
});
</script>
Nothing appears but errors like
GET http://localhost:8080/socket.io/?EIO=2&transport=polling&t=1462638049681-3 net::ERR_CONNECTION_REFUSED
and nothing on my server
any ideas to help me ? thanks :)
Your server is not listening on port 8080. That's why when you try to connect from browser to var socket = io.connect('http://localhost:8080');, it shows 'Connection Refused'.
This edit would work for you.
var express = require('express'); // call express
var app = express(); // define our app using express
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket){
console.log('a user connected');
console.log(socket);
socket.on('disconnect', function () {
console.log('socket disconnected');
});
io.emit('text', 'wow. such event. very real time.');
});
//Now server would listen on port 8080 for new connection
http.listen(8080, function(){
console.log('listening on *:8080');
});

Categories