All I'm working on a small game using node js, so I have a button and when I press the button a rectangle should be drawn in the canvas that is present on my Html page.
But I think my node js is loading faster than my Html, how can I make all my Html elements load and then node js execute.
Here is my code
index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Sanke Game</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<button type="submit" id = "smallButton" name="button">Draw</button>
<canvas id="canvas" tabindex="0" width="640" height="480"></canvas>
<script src="userInput.js"></script>
<script src="snake.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="client.js"></script>
</body>
</html>
snake.js
const gameBoard = document.getElementById("canvas");
const gameBoard_ctx = canvas.getContext("2d");
const bun = document.getElementById("smallButton");
//Generating Random Coordinate
function randomCoordinates(){
var startX = 40+Math.random()*560;
var startY = 40+Math.random()*400;
return [startX, startY];
}
// Drawing snake
function drawSnakePart(snakePart){
gameBoard_ctx.fillStyle = 'lightblue';
gameBoard_ctx.strokestyle = 'darkblue';
gameBoard_ctx.fillRect(snakePart[0], snakePart[1], 10, 10);
gameBoard_ctx.strokeRect(snakePart[0], snakePart[1], 10, 10)
}
function drawSnake(){
for(var i=0; i<8; i++){
drawSnakePart(randomCoordinates());
}
}
bun.addEventListener("click", function(){
alert("clicked");
drawSnake();
})
app.js
const express = require("express");
const http = require("http");
const app = express();
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
//Responding to Root request
app.get("/", function(req, res){
res.sendFile(__dirname + "/index.html")
})
//Responds if client request is made
app.get("/client.js", function(req, res){
res.sendFile(__dirname + "/client.js");
})
//Responds to css req
app.get("/styles.css", function(req, res){
res.sendFile(__dirname + "/styles.css");
})
//Responds to keyMovements
app.get("/userInput.js", function(req, res){
res.sendFile(__dirname+"/userInput.js");
})
app.get("/snake.js", function(req, res){
res.sendFile(__dirname+"/snake.js");
})
io.on('connection', function(socket){
console.log("User is connected");
socket.on("disconnect", function(){
console.log("User Disconnected");
})
socket.emit("serverToClient", "Hello World");
socket.on("clientToServer", function(event){
console.log(event);
})
socket.on("clientToClient", data => {
socket.broadcast.emit("serverToClient", data);
})
})
server.listen(3000, function(){
console.log("Listening to port 3000");
})
Related
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"
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
js application. Need help to resolve this issue.
I have app.js which is node, calls index.html. The index.html intern calls main.js function clicked. It works fine when I have funtion 'clicked()' embeded inside index.html using script tag. But does not work if function clicked is in a seperate js file. I think this is something regarding to node.js but unable to figure out. Please find my code below.
app.js
var http = require('http');
var fs = require('fs');
var express = require('express');
var path = require('path');
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
var request = require('request');
request('http://localhost:8000/test', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
});
var server = http.createServer(function(req,res){
console.log('Request was made:' + req.url);
res.writeHead(200,{'content-Type': 'text/html'});
var myReadStream = fs.createReadStream(__dirname + '/index.html','utf8');
myReadStream.pipe(res);
});
server.listen(3000,'127.0.0.1');
console.log('Listening on port 3000');
index.html
<!DOCTYPE html>
<html>
<head>
<title> Login</title>
<script type="text/javascript" src="main.js"></script>
<center>
<h1> Login </h1>
</center>
</head>
<body>
<center>
<input type="text" id="username" placeholder="UserName"></br>
<input type="password" id="password" placeholder="PassWord"></br>
<input type="button" value="Login" onclick="clicked()">
</center>
</body>
</html>
main.js
function clicked() {
var user = document.getElementById('username');
var pass = document.getElementById('password');
var checkuser = "test";
var checkpass = "123"
if (user.value == checkuser) {
if (pass.value == checkpass) {
window.alert("You are logged in as "+ "'"+user.value+"'");
open("http://www.yahoo.com");
}
else
window.alert("Incorrect username or Password");
}
else
window.alert("Incorrect username or Password");
}
ScreenShot of the Error:
This is because the Node.js server does not serve main.js correctly -- According to the browser's "Resources" panel, main.js is available, but its path is not /main.js.
Low level Node.js server code and Express framework code co-exist, which is not a good idea.
To solve the problem with low level Node.js code:
var server = http.createServer(function(req,res){
console.log('Request was made:' + req.url);
if (req.url === '/main.js') {
res.writeHead(200,{'content-Type': 'application/javascript'});
var jsReadStream = fs.createReadStream(__dirname + '/main.js','utf8');
jsReadStream.pipe(res);
return;
}
res.writeHead(200,{'content-Type': 'text/html'});
var myReadStream = fs.createReadStream(__dirname + '/index.html','utf8');
myReadStream.pipe(res);
});
To solve the problem with Express framework:
var http = require('http');
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.get('/main.js', function(req, res) {
res.sendFile(path.join(__dirname + '/main.js')); // where main.js located.
});
app.set('port', 3000);
var server = http.createServer(app);
server.listen(port);
You are using both http and express, which is probably unnecessary. I would serve static files with app.use(express.static('public')), per the docs. Then you can serve the index with
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/index.html'))
});
And start the server with app.listen(3000);
Whenever I go to http://localhost:8080/search (search.html), it loads all of the html, then it reaches the client-side javascript and crashes. The first console.log in searchClient.js works, but not the second. The error is that io is not defined.
server.js:
var http = require('http');
var express = require('express');
var anyDB = require('any-db');
var engines = require('consolidate');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var conn = anyDB.createConnection('sqlite3://riverdata.db');
app.engine('html', engines.hogan);
app.set('views', __dirname + '/templates');
app.use(express.static(__dirname + '/public'));
app.get("/", function(request, response){
response.render('home.html');
});
app.get("/search", function(request, response){
response.render('search.html');
});
io.on('connection', function(socket){
socket.on('join', function(){
});
socket.on('search', function(toShowList, conditionsList){
var data = conn.query('SELECT toShowList FROM riverdata WHERE conditionsList');
console.log("im in socket.on(search)");
socket.emit('data', data);
});
socket.on('disconnect', function(){
});
});
app.listen(8080);
searchClient.js:
console.log("begins");
var socket = io.connect();
console.log("keeps running");
window.addEventListener('load', function(){
console.log("page loads");
var search = document.getElementById("searchButton");
submit.addEventListener("click", search, false);
socket.emit('join');
socket.on('data', function(data){
console.log(data);
})
}, false);
function search(){
console.log("button clicked");
var toShowList = [];
var conditionsList = [];
socket.emit('search', toShowList, conditionsList);
}
search.html:
<!DOCTYPE HTML PUBLIC>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src='localhost:8080/socket.io/socket.io.js'></script>
<script type="text/javascript" src="/searchClient.js"></script>
<title>Envirostats Database</title>
<link rel="stylesheet" href="/style.css" type="text/css" />
</head>
<body class="search">
<form action="">
<input type="checkbox" name="data" value="data"> Show Date <br>
<input type="checkbox" name="data" value="river"> Show River <br>
</form>
<button id=searchButton> Search </button>
</body>
</html>
I made an online multiplayer game. I works perfectly when I run it with node.js command prompt on localhost:3000. But when I try to run it on the website it is not doing what my app.js file says it to do. my questions are;
How can I make my node.js project run on my website rather than on localhost?
What will the port be instead of 3000?
Can I do this by uploading some file into my website via ftp?
Here is my app.js file
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
var usernumm = 0;
var usernum1 = [];
app.use(express.static(__dirname + '/public'));
server.listen(3000);
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function(socket){
var endpoint = socket.manager.handshaken[socket.id].address;
console.log('***New connection from ' + endpoint.address + ':' + endpoint.port);
usernumm++;
io.sockets.emit('usernum', usernumm);
usernum1[usernumm] = endpoint.port;
console.log('usernum'+usernumm+'geldi'+findusernum());
socket.on('button1socket', function(){
io.sockets.emit('button1f', findusernum() );
console.log('user '+findusernum()+' pressed a button');
});
socket.on('buttonclickable', function(){
io.sockets.emit('buttonclickable1', findusernum() );
});
socket.on('disconnect', function () {
usernumm--;
io.sockets.emit('usernum', usernumm);
//sockets[usernum] = socket.port;
console.log('***Client disconnected');
});
//finds number of online users
function findusernum(){
for(var i = 0; i<9;i++){
if(usernum1[i] == endpoint.port){return i;}else{}
}
}
});
try:
var express = require('express');
var app = express();
var httpServer = require('http').Server(app);
var socketServer = require('socket.io')(httpServer);
var ip = 'iphere';
var port = 80;
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
socketServer.on('connection', function(socket){
console.log("A Client has connected.");
socket.on('disconnect', function(){
console.log("A Client has disconnected.");
});
});
httpServer.listen(port, ip, function(){
console.log("Listening to "+ip+":"+port);
});
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script type="text/javascript" src="http://ip:port/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket;
try{
socket = io("http://ip:port/", {'forceNew':true });
socket.on('connect', function(error){
if(error){
}
});
}catch(e){
}
</script>
</head>
<body>
</body>
</html>
after you have specified your ip and port
port forward the port you have specified to live your website/game using your router
then you can visit it with http://yourpublicip:port/
if its port 80 then visit the page without the port.