Socket.io files missing? - javascript

It's probably obvious, but I'm on this for more than 3 hours now, but I can't figure out the problem.
I just want to make a simple webpage, that can communicate with the server-side code.
I have the latest version of all the libraries.
My server-side code is:
//import libaries
global.express = require('express');
global.http = require('http');
global.socketio = require('socket.io');
global.app = express();
global.server = http.createServer(app);
global.io = socketio(server);
//serve files
app.use(express.static('public'));
//start listening
app.listen(80, () => {
console.log('listening...');
});
//socket
io.on('connection', (socket) => {
console.log('a user connected');
});
And my client-side code looks like this:
<script src="/socket.io/socket.io.js"></script>
<script>
let socket = io();
</script>
<script src="sketch.js"></script>
This should work, but I get this error every time (in the client side-console):
GET http://localhost/socket.io/socket.io.js net::ERR_ABORTED 404 (Not Found)
I know there is a lot of questions like this, but they are usually outdated.
PS: If I remove the socket part, express functions properly.

Okay so it seems like you're creating your own http server and then attaching socket.io to it. But then instead of listening to said server, you listen to Express. Either do
server.listen(80, () => {
console.log('listening...');
});
or just use Express' server by
var server = app.listen(80);
var io = require('socket.io').listen(server);
Also, if you're building a simple website, you might not need socket.io at all.

Related

What do I replace "http://localhost:3000" with when using a server and not local machine?

I've been doing a lot of online courses with node and express. I want to get sockets.io to work but I can't even establish a connection at the moment. I am using a cPanel virtual private server and running code in the server terminal and then trying to use a website hosted on the server to access the .js file running on the server.
I've tried all sorts of different things but I'm reducing it to its most basic level to try get a connection. All the videos I've seen are running on a local machine and using the command prompt on a local machine to run the .js file and the browser to access http://localhost:3000.
The .js file I'm running on my cPanel server looks like this;
var express = require('express');
var app = express();
app.get('/', function(req,res){
res.send('Hello world 2');
})
app.listen(3000);
So how do I then access that via the browser? I have tried http://mywebsite.com:3000 and http://11.22.33.444:3000 if 11.22.33.444 is the server ip, but the browser just times out and there is no output in the server console.
ultimately I need to run a socket.io command that looks like this;
var socket = io.connect('http://localhost:3000');
and in all the tutorials I've seen they use this localhost:3000 but no one explains how to access this if its on an actual server so I'm pretty lost.
There are other examples like;
...
const http = require('http').createServer();
...
http.listen(3000 => () => {
console.log('listening on port 3000');
});
That's just a snippet of the code but I'm wondering how I then access that 3000 port from the browser without http://localhost:3000
IF you read the docs you will see that there is a guide how to connect it with express: https://socket.io/docs/
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(3000);
// WARNING: app.listen(3000) will NOT work here!
app.get('/', function (req, res) {
res.status(200).json({ message: "Connected" });
});
io.on('connection', function (socket) {
console.log("somebody connected");
});
Think I just solved it. I tried a different port and it worked :/
No need to specify any address in io.connect()
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
http.listen(process.env.PORT || 3000, function() {
});
<script src="/socket.io/socket.io.js"></script>
var socket = io.connect();

Socket.io not working with external access without express

My question is am i possible to run the socket.io lib without using express? The thing is i want to make node as an external web socket server which just receives sockets connection and callbacks and just simply reply to them, not to make own routes or send page view (I'm using codeigniter for that work).
My current test app is like this on Server:
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 4000;
server.listen(port, function() {
console.log('Server listening at port %d', port);
});
io.on("connection", function (socket) {
console.log('A new socket has joined: ' + socket.id);
var tweet = {user: "nodesource", text: "Hello, world!"};
// to make things interesting, have it send every second
var interval = setInterval(function () {
socket.emit("tweet", tweet);
}, 1000);
socket.on("disconnect", function () {
clearInterval(interval);
});
});
On Client:
<script>
const socket = io('http://localhost:4000/node_server');
socket.on('disconnect',function(){
alert('Im not connected, server is down');
});
socket.on("tweet", function(tweet) {
// todo: add the tweet as a DOM node
console.log("tweet from", tweet.username);
console.log("contents:", tweet.text);
});
My problem is that i have tested with express the chat example of socket.io and it works ofc but they use route and send the page and in my case i just want my other external page to communicate with node and not node sending me the page. Basically when i trigger some emit or function at server or client it does not fire just on server the connection but nothing else (p.s: also used io.sockets.on and doesn't work too)
If anyone has passed this and knows what my problem might be, i'll be glad.
Okay let's start off with something really basic here is our express server which is only hosting our socket application:
var app = require("express")();
var server = require("http").createServer(app);
var io = require("socket.io")(server);
var port = process.env.PORT || 4000;
server.listen(port, function() {
console.log("Server listening at port %d", port);
});
io.on("connection", function(socket) {
console.log("A new socket has joined: " + socket.id);
socket.on("hello", function(data) {
console.log(data);
});
});
You already understand that much but, it's important to note that this server will listen for any socket connections from any address. This is important to keep in mind.
Now let's look at the client html file
<html>
<body>
<button id="hiBtn">Say Hi to your server</button>
<!-- You only need to include the client file here -->
<script src="https://rawgit.com/socketio/socket.io-client/master/dist/socket.io.js" </script>
</script>
<script>
const serverLocation = "localhost:4000" // or whatever your server location is
const socket = io(serverLocation);
window.onload = function () {
document.getElementById("hiBtn").addEventListener("click", function () {
socket.emit("hello", "Hi there, this is the client speaking");
})
}
</script>
</body>
</html>
Notice how I do not have <script src="/socket/socket.io"> this is because this html file is being hosted on a completely separate client. You need to simply include the client socket.io file here which is usually located in node_modules\socket.io-client\dist\socket.io.js if you installed it via NPM. Or you can use the url I provided in my example. Just make sure that serverLocation points to your express server and you're all set.
P.S. for this example I tested it by hosting the html file on port:5000 and the express server on port:4000 if you were curious.

Client unable to connect to server with socket.io

I'm having trouble with being able to connect to my node.js server from an external domain. It works fine when running it locally using the http web server through node however when connecting externally, it loads the socket.io.js file just fine but when trying to use the socket it removes the port from the URL and cannot connect.
Instead of doing this in the network requests:
http://external-domain.com:3000/socket.io/?EIO=3&transport=polling&t=M06GOUU
it does this:
http://external-domain.com/socket.io/?EIO=3&transport=polling&t=M06GOUU
I'm not sure how to make it not remove the port from the connection. How do I go about fixing this?
SERVER
const path = require('path');
const http = require('http');
const express = require('express');
const socketIO = require('socket.io');
const publicPath = path.join(__dirname, '../public');
var app = express();
var server = http.createServer(app);
var io = socketIO(server);
app.use(express.static(publicPath));
server.listen(3000, () => {
console.log(`Server is up on port 3000`);
});
CLIENT SCRIPT TAG
<script src="http://external-domain.com:3000/socket.io/socket.io.js"></script>
CLIENT JS ON A DIFFERENT DOMAIN
var socket = io();
socket.connect('http://external-domain.com:3000');
socket.on('connect', function () {
console.log('Connected to server.');
});
Change from this:
var socket = io();
socket.connect('http://external-domain.com:3000');
to just this:
var socket = io("http://external-domain.com:3000");
And, you don't use the socket.connect() as you will already have requested the connection with the io("http://external-domain.com:3000"); call.
Explanation
The code:
var socket = io();
uses the page URL to connect to a socket.io server at that origin. That is not what you want (apparently).
If you wanted to use the .connect() method, it would be like this:
var socket = io.connect("http://external-domain.com:3000");
Note: var socket = io(url) is simply a shortcut for var socket = io.connect(url).
socket.connect() does not accept a URL as a parameter so you simply weren't using that correctly. It's just a synonym for socket.open().
Use io.connect("url")
var socket = io.connect("http://external-domain.com:3000", { rejectUnauthorized: false });
// { rejectUnauthorized: false } is an optional parameter.
Hope this works for you.

Using socket io without returning the index.html throws an error

I would like to setup websocket without necessarily having to return the index.html file
Am still new to the socket io and this is what i have tried
installed socket io via
npm install socket.io --save
created index.js
var http = require('http');
var fs = require('fs');
// Loading socket.io
var io = require('socket.io');
// When a client connects, we note it in the console
io.sockets.on('connection', function (socket) {
console.log('A client is connected!');
});
server.listen(1100);
Now when i run node index am getting an error
io.sockets.on('connection', function (socket) {
^
TypeError: Cannot read property 'on' of undefined
What am trying to do is connect the websocet to my vuejs client side so ive skipped the part to display html part since i dont want to display html but to use the socket events.
where am i going wrong?
Hey you need to attach socket.io to an http server for your code to work and listen to incoming events.
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io').listen(server);
//io.on is the shorter form of io.sockets.on
io.on('connection', function(socket){
console.log('user connected');
});

nodejs socket.io GET http://domain/socket.io/?EIO=3&transport=polling&t=LrTVonQ status of 404 when importing socket.io

My problem is simple I'm actually getting an error 404 when I'm trying to import socket.io on my web page. I'm using
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
to import socket.io.
If I remove this line form my head tag, I'm fine but when it's there, I see in the dev tool the 404 error and my counter is not even working.
I am trying to make a live viewer count for one of my website but I never really use Node.js so this is why I have some trouble. Please forgive me if there is an error in my script.
For the serverside script, the file is called: viewercounter.js and this is the code
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = 8001;
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
app.use(express.static(__dirname + '/public'));
var count = 0
io.on('connection', function(socket) {
count++;
socket.broadcast.emit('userupd', {
numUsers: count
});
console.log(count);
socket.on('disconnect', function(){
count--;
socket.broadcast.emit('userupd', {
numUsers: count
});
console.log(count);
});
});
Then I placed the clientside script directly in my page instead of making a new file, I did not really see the point of it. Anyway, the file is called: index.php
and the code is at the end of the file just before the end of the body tag and there not other js before the code.
<script type="text/javascript">
$(function() {
var socket = io();
socket.on('userupd', function (data) {
$('.counter').html(data);
});
});
EDIT
By looking more deeper, I've been able to understand that it's a XMLHttpRequest problem. In fact, when the socket.io code that I just imported try to perform xhr.send(this.data) the error appears. Anyone knows how I can solve this ?
https://gyazo.com/53f64081a92b449e157df76c6c570178
EDIT2
After changing the port in the file viewcounter.js. It looks like this:
// Setup basic express server
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = 80;
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
// Routing
app.use(express.static(__dirname + '/public'));
var count = 0
io.on('connection', function(socket) {
count++;
socket.broadcast.emit('userupd', {
numUsers: count
});
console.log('New user: ');
socket.on('disconnect', function(){
count--;
socket.broadcast.emit('userupd', {
numUsers: count
});
console.log('Neg user:');
});
});
If your web page is coming from an Apache web server on port 80 and you want to create a socket.io server in node.js on the same host, then you need to pick a new port for that socket.io server and when you connect to the socket.io server, you need to identify the port you want to connect to because the default will be port 80, but that's not where your socket.io server is.
I'd suggest using port 8001 like you originally had for your socket.io server. Please change your node.js code back to that.
Then, you can change the socket.io code in your page from this:
<script type="text/javascript">
$(function() {
var socket = io();
socket.on('userupd', function (data) {
$('.counter').html(data);
});
});
</script>
to this:
<script type="text/javascript">
$(function() {
var url = window.location.protocol + "//" + window.location.hostname + ":8001";
var socket = io(url, {transports: ['websocket'], upgrade: false});
socket.on('userupd', function (data) {
$('.counter').html(data);
});
});
</script>
This will connect socket.io to the same protocol and host as your web page, but a different port and it will use only a webSocket so you don't run into cross origin issues with socket.io's usual attempt to initiate a connection with Ajax polling.
If your socket.io server is actually on a different host than your Apache server, then you need to put that host in the URL rather than window.location.hostname.

Categories

Resources