I have made a JS game. However, nothing shows up on the screen on localhost. When I check the console, I get the following error:
GET http://127.0.0.1:5500/socket.io/?EIO=3&transport=polling&t=NMFSX-v 404 (Not Found)
What does this error mean? How do I fix it?
code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../css/game.css">
<title>Document</title>
<canvas id="ctx" width="500" height="500" style="border: 1px solid #000000;"></canvas>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
var ctx = document.getElementById("ctx").
getContext("2d");
ctx.fint = '30px Arial'
var socket = io();
socket.on('newPosition', function(data) {
ctx.clearRect(0, 0, 500, 500);
ctx.fillText('P', data.x, data.y);
});
</script>
</head>
<body>
<!-- <div class="circle"></div> -->
<script src="../js/game.js"></script>
<script src="../js/server.js"></script>
</body>
</html>
var express = require('express');
var app = express();
var serv = require('http').Server(app);
app.get('/', function(_req, res){
res.sendFile(__dirname + '../clients/index.html');
});
app.use('../clients', express.static(__dirname + '../clients'));
serv.listen(2000);
console.log("Server started.");
var SOCKET_LIST = {};
var io = require('socket.io') (serv,{});
io.sockets.on('connection', function(socket){
socket.id = Math.random()
socket.x = 0;
socket.y = 0;
SOCKET_LIST[socket.id] = socket;
});
setInterval(function(){
for(var i in SOCKET_LIST){
var socket = SOCKET_LIST[i];
socket.x++
socket.y++
socket.emit('newPosition', {
x:socket.x,
y:socket.y
})
};
},1000/25);
Please can you make sure to post potential solutions in the Answers section?
Thank you SO much for your help!!!
**Edit: Here is a screenshot of the error:
I think the error starts under the line
var io = require('socket.io') (serv,{});
try this block for the lines under instead
io.sockets.on('connection', function(socket){
var socketID=Math.floor(Math.random())*80
while(SOCKET_LIST[socketID]!=undefined){
socketID=Math.floor(Math.random())*80
}
//all that drama above is to(at least meant to) prevent socket overlap(just in case that solves a problem)
socket.id = socketID
socket.x = 0;
socket.y = 0;
SOCKET_LIST[socket.id] = socket;
});
setInterval(function(){
Object.keys(SOCKET_LIST).forEach((a,i)=>{
var socket = SOCKET_LIST[i];
socket.x++
socket.y++
socket.emit('newPosition', {
x:socket.x,
y:socket.y
})
})
},1000/25);
if this doesn't work then the problem is what the frontend tries to access(reason for that 100% strange link it tried to access)
404 (Not Found)
It is the http-error-code for not finding an url.
Edit:
In your given script you call the js-file from the Content Delivery Network of socket.io: "https://cdn.socket.io/socket.io-1.4.5.js".
Check your local script if you mayby made a mistake with transforming it to "http://127.0.0.1:5500/socket.io/?EIO=3&transport=polling&t=NMFSX-v"
Related
I've spent days trying to figure out why this is not working, but I didn't get anything out of it.
I tried some other answers about this topic, but none seemed to work for me.
Answers tried:
How to resolve a Socket.io 404 (Not Found) error?
socket.io: Failed to load resource
GET http://localhost:3000/socket.io/socket.io.js 404 (Not Found)
Error: http://localhost:3001/socket.io/ 404 (Not Found)
Socket.io http://localhost:3000/socket.io/socket.io.js 404 (Not Found) - How to configure socket.IO - nodejs, apache2, websockets
Socket.io 404 Not Found
This is my code.
File server.js:
//Dependencies
var express = require('express');
var io = require('socket.io').listen(server);
//Dependencies
//Global variables
var app = express();
var PORT = 3000;
const ROOT = {root : __dirname};
var players = [];
//Global variables
var server = app.listen(PORT, function() {
console.log("Server process started successfully on port " + PORT + "\n");
});
app.get('/', function(req, res) {
console.log("Server called from " + req.socket.remoteAddress + ":" + req.socket.remotePort + "\n");
res.sendFile('html/access.html', ROOT);
});
app.get('/gameSelection', function(req, res) {
let name = req.query.name;
players.push(name);
console.log("New player named " + name + " joined the hub." + "\n");
console.log("Total active players: " + players.length + "\n");
console.log("Complete list of active players: " + players + "\n");
res.sendFile('sketches/menu/index.html', ROOT);
});
app.use(express.static(__dirname + '/sketches/menu'));
io.sockets.on('connection', function(socket){
console.log("We have a new client: " + socket.id);
});
File access.html:
<!DOCTYPE html>
<html>
<head>
<title>Welcome traveler</title>
</head>
<body>
<form method="GET" action="/gameSelection">
Name: <input type="text" name="name" placeholder="Insert your name..." required>
<input type="submit" value="submit">
</form>
</body>
</html>
File menu.js:
const socket = io.connect(window.location.origin);
function setup()
{
createCanvas(600, 400);
ellipse(100, 100, 50, 50);
}
function draw() {}
File index.html:
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script language="javascript" type="text/javascript" src="libraries/p5.min.js"></script>
<script language="javascript" type="text/javascript" src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script language="javascript" type="text/javascript" src="menu.js"></script>
<style> body { padding: 0; margin: 0; } </style>
</head>
<body>
</body>
</html>
As shown by the code, I'm trying to connect via socket.io a p5js page to my node server.
But when I get to the index.html page I get this error:
GET http://localhost:3000/socket.io/?EIO=3&transport=polling&t=NEsXBrx 404 (Not Found)
Request.create # socket.io-1.4.5.js:1
Request # socket.io-1.4.5.js:1
XHR.request # socket.io-1.4.5.js:1
XHR.doPoll # socket.io-1.4.5.js:1
Polling.poll # socket.io-1.4.5.js:1
Polling.doOpen # socket.io-1.4.5.js:1
Transport.open # socket.io-1.4.5.js:1
Socket.open # socket.io-1.4.5.js:1
Socket # socket.io-1.4.5.js:1
Socket # socket.io-1.4.5.js:1
Manager.open.Manager.connect # socket.io-1.4.5.js:2
(anonymous) # socket.io-1.4.5.js:3
I really cannot understand what's wrong with my code, so I hope someone can help.
Thanks in advance.
You are executing this line of code:
var io = require('socket.io').listen(server);
Before server has a value. So, you end up doing this:
var io = require('socket.io').listen(undefined);
Which will probably create a separate web server on a default port which isn't the port you're trying to connect on.
You need to execute this line of code:
var io = require('socket.io').listen(server);
AFTER server already has a value.
Note, if you use const and let and get rid of all occurrences of var, then Javascript would appropriately tell you this was an error because you're attempting to use the variable before it's declaration. That is technically legal with var, but obviously leads to programming mistakes like this. Use let and const instead of var and you can't make this type of mistake nearly as easily.
So I have a Raspberry Pi 4 and im trying to receive data from a JSON file and display it on a text element on my website. sorry if im totally wrong, it's my second day with a Raspberry Pi. I have done basic things like turn an LED on, thanks to w3schools. Im trying to make a bot hosting tool thing for myself, where it will display amount hosted on a TV
index.html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="index.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
</head>
<body>
<div class="container">
<h1>Bots Hosted:</h1>
<h2 id="bot-qty">0</h2>
</div>
</body>
<script>
var socket = io();
window.addEventListener("load", function() {
var bot_count = document.getElementById("bot-qty");
var times_ran = 0;
const interval = setInterval(function() {
socket.emit("request-count", times_ran);
times_ran++;
}, 20000);
})
socket.on('request-count', function(data) {
document.getElementById("bot-qty").innerText = data;
})
</script>
</html>
webserver.js:
var http = require('http').createServer(handler);
var fs = require('fs');
var io = require('socket.io')(http);
http.listen(1337);
function handler(req, res) {
fs.readFile(__dirname + '/public/index.html', function(err, data) {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/html' });
return res.end("404 Not Found");
}
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(data);
return res.end();
});
}
io.sockets.on('connection', function(socket) {
socket.on('request-count', function(data) {
var bot_count = JSON.parse(fs.readFileSync("config.json", "utf8"));
console.log(bot_count);
socket.emit('request-count', bot_count);
});
});
In console, it says
GET <long_url_here> net::ERR_NAME_NOT_RESOLVER
In the index.html you initialize a new Socket instance by writing
var socket = io();
You don't provide any url, so the socket.io-client will use the default window.location as can be seen here. This might be a problem, so try to set a specific url, e. g.
var socket = io('http://localhost');
or (also specifying the port)
var socket = io('http://localhost:1337');
Also try to make sure that you run your webserver.js with node webserver.js prior to open the website.
Also see this discussion on GitHub.
This is my server side code for creating connection to the socket.I am using node.js code and using socket.io in that.
const path = require('path');
const http = require('http');
const express = require('express');
const socketIO = require('socket.io');
const port = process.env.PORT || 3000;
var app = express();
var server = http.createServer(app);
var io = socketIO(server);
io.on('connection', (socket) => {
console.log('New user connected');
})
and this is my client side code i am using plain javascript as a client and I am using 2.1.1 version of socket.io, I am getting io not defiend error,I am very new to socket.io please help me one this one.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
</head>
<body>
<script>
$(document).ready(function(){
var socket = io('http://localhost:3000');
console.log("Socket connected"+socket.connected);
socket.on('notification', function(value){
//insert your code here
});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
</body>
</html>
Your first script (the one using io) is running before your other scripts (the jQuery and Socket scripts). Move your scripts around like so:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
<script>
$(document).ready(function() {
var socket = io('http://localhost:3000');
console.log("Socket connected" + socket.connected);
socket.on('notification', function(value) {
//insert your code here
});
});
</script>
As I'm new to web development this might be wrong, but I would try to place your script below the script where you import socket.io.js
In your function you are calling io but before you call it it doesn't seem to be declared.
Hope this works.
So, my program gets data from udp server and i just want to display it in list in HTML page 1 by 1 when it updates.
In console it works, but how to do it on page?
I got this code
index.js
var dgram = require('dgram'),
server = dgram.createSocket('udp4'); //this server gets data from udp packet
var msg;
server.on('message', function (message, rinfo) {
msg = message.toString('ascii'); //udp packet data to string
console.log(msg);
});
server.on('listening', function () {
var address = server.address();
console.log('UDP Server listening ' + address.address + ':' + address.port);
});
server.bind(8007);
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket) {
var tm = setInterval(function() {
socket.emit('datafromserver', {'datafromserver': msg});
}, 500);
socket.on('disconnect', function() {
clearInterval(tm);
});
});
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
and html page
<!doctype html>
<html>
<head>
<title>Scoreboard</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
</style>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io.connect('http://192.168.1.162:3000/');
socket.on('#dataonscreen', function(data) {
$('#dataonscreen').html(data.datafromserver);
console.log(data.datafromserver);
});
</script>
<ul id="dataonscreen"></ul>
</body>
</html>
I can't understand why this isn't working and how to fix it.
Please help!
Your socket.io server emits datafromserver while your code listens for #dataonscreen
Change either so that they are the same value and your code should work. I'm not sure how you have console output since the event is not being listened for
I have two clients which can interchange some data over socket.io. I also have a server. What i need to do is i want to send data from client 1 to client 2 over a socket and i am unable to figure out that how i can achieve it.Please note that client 1 and client 2 are different html pages.
Server.JS
var express = require('express');
var app = express();
var fs = require('fs');
var path = require('path');
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 3000;
var ip=process.env.IP||"192.168.1.5";
app.use(express.static(__dirname));
server.listen(port,ip, function () {
console.log('Server listening at port %d ', port);
});
app.get('/index', function(req, res) {
res.sendFile(path.join(__dirname,'/test.html'));
})
app.get('/index1', function(req, res) {
res.sendFile(path.join(__dirname,'/test1.html'));
})
io.on('connection', function (socket) {
socket.on('broadcast', function (message) {
console.log(message);
socket.broadcast.emit('message', message);
});
console.log("connected");
});
Client1.JS
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script >
var socket = io.connect();
socket.emit('broadcast',"Broadcasting Message");
socket.on('message', function (data) {
alert(data)
});
</script>
</body>
Client2.JS
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script >
var socket = io.connect();
socket.on('message', function (data) {
alert(data)
//socket.emit('message',"Hello world");
});
</script>
</body>
Ok, here is what I did on my local and you may change it by your needs.
server.js
var io = require('socket.io')(80);
io.on('connection', function (socket) {
socket.on('broadcast', function (message) {
console.log(message);
socket.broadcast.emit('message', message);
});
console.log("connected");
});
client1.js
var socket = io.connect('ws://127.0.0.1');
socket.emit('broadcast',"Broadcasting Message");
socket.on('message', function (data) {
$('#client1').html(data);
});
client2.js
var socket = io.connect('ws://127.0.0.1');
socket.on('message', function (data) {
$('#client2').html(data);
});
index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src='https://code.jquery.com/jquery-1.12.4.min.js'></script>
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
<script type="text/javascript" src="client1.js"></script>
<script type="text/javascript" src="client2.js"></script>
</head>
<body>
<div> <h1> CLIENT 1 </h1><div id="client1"></div></div>
<div> <h1> CLIENT 2 </h1><div id="client2"></div></div>
</body>
</html>
On a termminal after you run, node server.js and reload your page, you will see client2 will have Broadcasting message html appended
Make sure to pass the URL to the server when instantiating WS on the client side... for example var socket = io.connect('http://localhost');
On the server side, each WS connection with each client is a unique instance. That is to say that for this purpose you must be deliberate about which WS connection you target when emitting events.
The first thing to solve is how to associate WS connection instances with specific clients. The answer to this is to use a map/dictionary/plain ol' javascript object with some sort of unique client identifier as the key and the instance of the WS connection as the value. Pseudo-code:
let connections = { 'client1': WSinstance, 'client2': WSinstance };
You would add to this object every time you create a new WS instance. Assuming you have a way to uniquely identify a client and that is stored in the variable clientId, you could do the following:
io.on('connection', function (socket) {
connections[clientId] = socket;
}
Now if you want to emit a message to just client1 you can use the WS instance associated with them by grabbing it from the object connections.client1 or if you want to target client2 connections.client2