hey guys im working on a project with some friends and we want our server on openshift it runs without errors but it always gives cannot get /
i tried to look for solutions and tried many but it just doesent fix it.
any ideas ?
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io').listen(server);
//
app.use(express.static(__dirname + '/public'));
app.use('/static', express.static(__dirname + '/public'));
server.listen(process.env.OPENSHIFT_NODEJS_PORT, process.env.OPENSHIFT_NODEJS_IP);
io.on('connection', onSocketConnection);
var players = [];
var npc1 = new Player(1049, 980);
npc1.id = "Johan Kruijs";
npc1.color = "gold";
npc1.name = "[NPC] Johan Kruijs";
players.push(npc1);
function onSocketConnection(client) {
console.log("Player has connected: ");
client.on("disconnect", onClientDisconnect);
client.on("new player", onNewPlayer);
client.on("move player", onMovePlayer);
};
function onClientDisconnect() {
var removePlayer = playerById(this.id);
if (!removePlayer) {
console.log("Player not found: " + this.id);
return;
}
console.log(removePlayer.name + " has disconnected.");
players.splice(players.indexOf(removePlayer), 1);
this.broadcast.emit("remove player", {
id: this.id
});
};
function onNewPlayer(data) {
var newPlayer = new Player(data.x, data.y);
newPlayer.id = this.id;
newPlayer.name = data.name;
newPlayer.color = data.color;
this.broadcast.emit("new player", {
id: newPlayer.id,
x: newPlayer.x,
y: newPlayer.y,
name: newPlayer.name,
color: newPlayer.color
});
var i, existingPlayer;
for (i = 0; i < players.length; i++) {
existingPlayer = players[i];
this.emit("new player", {
id: existingPlayer.id,
x: existingPlayer.x,
y: existingPlayer.y,
name: existingPlayer.name,
color: existingPlayer.color
});
};
players.push(newPlayer);
console.log(" - name: [" + newPlayer.name + "]")
console.log(" - id: [" + newPlayer.id + "]");
};
function onMovePlayer(data) {
var player = playerById(data.id);
player.x = data.x;
player.y = data.y;
player.id = data.id;
io.emit("move player", {
id: data.id,
x: data.x,
y: data.y
})
};
function playerById(id) {
var i;
for (i = 0; i < players.length; i++) {
if (players[i].id == id)
return players[i];
};
return false;
};
function Player(xpos, ypos) {
var result = {
x: xpos,
y: ypos,
id: 0
}
return result;
}
path --
In the screenshot you shared, the folder name is Public and not public, in osX (I assume that is what you are using from the screenshot), Public and public are different.
If you write this,
app.use(express.static(__dirname + '/Public'));
Things should start working.
Plus if you wanna set a default page, i.e. when user visits / and you want your /index.html to be served, you can do it like
app.use('/', express.static(__dirname + '/Public', {index: "index.html"}));
I hope this resolves your issue!!
Related
I was testing a SSE node express chat in localhost.It was working perfectly. I was including a chat_server in a demo with hapijs as modular server...and it complain about the express syntax. How can I migrate the code to the right syntax in hapijs?
I am trying to solve changing writeHead and write methods because it's complaing about and adding stream package after searching answers in internet.
/*
* Request handlers
*/
function handleGetChat(req, res) {
console.log('handleGetChat received.');
// res(chatStream).code(200).type('text/event-stream').header('Connection', 'keep-alive').header('Cache-Control','no-cache');
// chatStream.write('\n');
(function(clientId) {
clients[clientId] = res;
clientNames[clientId] = req.params.name;
console.log('name {$req.params.name}');
req.on("close", () => {
delete clients[clientId];
actUserName = "";
sendText(clientNames[clientId] + " disconnected!", false);
delete clientNames[clientId];
});
})(++clientId);
sendText(req.params.name + " connected!", false);
let allMates = "";
for (cliId in clientNames) {
allMates += `${clientNames[cliId]}`;
if (cliId < clientId) allMates += " ";
}
sendText(`logged in [${allMates}]`, false);
}
let sendText = (text, showUserName = true) => {
for (clientId in clients) {
allMates += `${clientNames[cliId]}`;
if (cliId < clientId) allMates += " ";
}
sendText(logged in [${allMates}], false);
}
let sendText = (text, showUserName = true) => {
for (clientId in clients) {
let data = "";
let date = new Date();
let timestamp = `[${date.getHours()}:${date.getMinutes()}]`;
if (showUserName) {
data = `data: ${timestamp} <${actUserName}> ${text}\n\n`;
} else {
data = `data: ${timestamp} ${text}\n\n`;
}
//chatStream.push('data: ' + "\n\n");
}
};
function handleWriteChat(req, res) {
actUserName = req.body.name;
sendText(req.body.text);
res.json({ success: true });
}
The commented lines in the code above are the lines with syntax error in hapi. I was already changing the originals write and writeHead with chatstream.
I have a problem with node.js and sequelize findOne(). I want to find new students, that I want to add to the DB (var novi), and the ones that already exist, I just want to update their field (var stari). Everything works as expected, only when I want to return JSON with how many new students I added to the DB, and how many are updated, values of stari and novi, go back to 0, but the counting is good, I checked. I know the problem is with asynchronous call, but I don't know how to fix.
app.post('/student', function(req,res) {
var imeGodine = req.body['godina'];
//POMOĆNE SKRIPTE BitBucket.js i citanjeGodina.js
var broj = 0;
var stari = 0;
var novi = 0;
db.godina.findOne({where:{nazivGod:req.body.godina}}).then(god => {
var studenti = req.body.studenti;
db.student.count().then (ranijeStudenata => {
for(var i = 0; i<studenti.length; i++) {
var ime = studenti[i].imePrezime;
var ind = studenti[i].index;
db.student.findOne({where:{index :studenti[i].index}}).then(stud => {
if (stud == null) {
novi++;
db.student.create({imePrezime:ime, index : ind}).then(noviStudent => {
god.addStudenti(noviStudent);
});
}
else if (stud != null) {
stari++;
god.addStudenti(stud);
}
});
broj++;
}
var brojNovih = broj - ranijeStudenata; //ne koristi se, ali možda hoće
res.set("Content-Type", "application/json");
res.status(200).send(JSON.stringify({message: "Dodano je " + novi + " novih studenata i upisano " + stari + " na godinu " + imeGodine}));
});
});
});
Picture of code
You can use async/await to do counting in a synchronous way.
'use strict';
app.post('/student', async function (req, res) {
var imeGodine = req.body['godina'];
var {studenti} = req.body;
var broj = 0;
var stari = 0;
var novi = 0;
let god = await db.godina.findOne({where: {nazivGod: req.body.godina}});
let ranijeStudenata = await db.student.count(); // ranijeStudenata not used?
for (var i = 0; i < studenti.length; i++) {
var ime = studenti[i].imePrezime;
var ind = studenti[i].index;
let stud = await db.student.findOne({where: {index: studenti[i].index}});
if (stud === null) {
novi++;
let noviStudent = await db.student.create({imePrezime: ime, index: ind});
god.addStudenti(noviStudent);
} else if (stud !== null) {
stari++;
god.addStudenti(stud);
}
broj++;
}
return res.status(200).send({
message: "Dodano je " + novi + " novih studenata i upisano " + stari + " na godinu " + imeGodine
});
});
So I am trying to make a node multiplayer game using socket.io and the HTML5 canvas.
I have gotten the objects to appear on each other's client canvas, but their positions are way off. How do I position the objects so that they will show up properly on the client side?
Here is my code.
Client:
var socket;
var ship;
var cnv;
function setup() {
cnv = createCanvas(1000, 1000);
translate(120, 120);
var x = (windowWidth - width) / 2;
var y = (windowHeight - height) / 2;
cnv.position(x, y);
background(51);
socket = io('http://localhost:3000');
ship = new Avatar();
socket.on('pos', newDrawing)
var data = {
x:ship.pos.x,
y:ship.pos.y,
r:ship.r,
heading:ship.heading
}
socket.emit('start', data)
}
function newDrawing(data){
for(var i =0; i< data.length;i++){
if(data[i].id != socket.id){
rotate(data[i].h+ PI/2)
var x=data[i].x;
var y= data[i].y
var r = data[i].r
console.log(r)
triangle(x+ -data[i].r, y+data[i].r, x+data[i].r,y+data[i].r,x+ 0,y+-data[i].r)
}
}
}
function keyPressed(){
if(keyCode == 65){
ship.setRotation(-0.1)
//ship.vel.x += -speed;
}
//Right
if(keyCode == 68){
ship.setRotation(0.1)
}
if(keyCode == 87){
ship.boosting(true);
}
}
function keyReleased(){
ship.setRotation(0);
ship.boosting(false);
}
function draw() {
//background(51);
//console.log(cnv)
ship.render();
ship.turn()
ship.update();
ship.edges();
var data = {
x:ship.pos.x,
y:ship.pos.y,
r:ship.r,
heading:ship.heading
}
socket.emit('pos', data)
//clear()
}
Object
class Avatar{
constructor(){
this.pos=createVector(1000,1000);
this.r=50;
this.vel=createVector(0,0)
this.color = 'red';
this.move=false;
this.heading=0;
this.rotation=0;
this.isBoost=false;
}
update(){
if(this.isBoost){
this.boost();
}
this.pos.add(this.vel);
this.vel.mult(.99)
}
setRotation(a){
this.rotation=a;
}
boosting(a){
this.isBoost=a;
}
boost(){
var force= p5.Vector.fromAngle(this.heading);
this.vel.add(force);
}
turn(){
this.heading+= this.rotation;
}
edges(){
if(this.pos.x>width+this.r){
this.pos.x=-this.r;
} else if(this.pos.x<-this.r){
this.pos.x=width +this.r;
}
if(this.pos.y>height+this.r){
this.pos.y=-this.r;
} else if(this.pos.y<-this.r){
this.pos.y=height +this.r;
}
}
render(){
//clear()
//translate(this.pos.x, this.pos.y)
rotate(this.heading+ PI/2)
//rect(this.r,-this.r,this,this.r)
fill(this.color)
triangle(-this.r,this.r,this.r,this.r,0,-this.r)
}
}
Server
var express=require('express');
var app=express();
var server = app.listen(3000)
var ships=[];
function Avatar(id,x,y,r,h){
this.id=id;
this.x = x;
this.y= y;
this.r=r;
this.h=h;
}
console.log("Server on %s", server.address().port)
// function listen(){
// var host= server.address().address;
// var port= server.address().port;
// console.log('Server running on %s',port )
// }
app.use(express.static('public'));
var socket=require('socket.io');
var io=socket(server);
io.sockets.on('connection',function(socket){
console.log("New Socket:" + socket.id)
socket.on('start',function(data){
ships.push(new Avatar(socket.id, data.x, data.y, data.r, data.heading));
//console.log(ships)
})
socket.on('pos',function(data){
var ship;
for(var i =0; i< ships.length; i++){
if(ships[i].id == socket.id){
ships[i].x=data.x;
ships[i].y=data.y;
ships[i].r=data.r;
ships[i].h=data.heading;
}
}
//console.log(ships[0])
//console.log(ships)
//console.log(socket.id)
//io.sockets.emit('pos',ships)
socket.broadcast.emit('pos',ships)
})
socket.on('disconnect' , function(){
for(var i =0; i< ships.length; i++){
if(ships[i].id == socket.id){
console.log(socket.id + " Has Left")
ships.splice(i,1);
}
}
})
})
Part of the issue I am seeing is that the other clients objects are being drawn as though their point of origin is not in the center of its own object.
I figured out why it was an issue. I was unaware that the translate and rotate functions were not object specific. Meaning, that when I was rotating for my client, it was rotating the perspective of the canvas, not the object. So any other objects would be visibly rotating around it.
I am using RecordRTC from recording webrtc meeting. After implementing recording, when I test this application if both client are on the same system then its working fine. When I test this application on different system it isn't working fine and meeting is not recorded.
Here this is my code from stop recording client side.
recordRTC.stopRecording(function (videoURL) {
console.log('recordRTC.stopRecording Function inside');
SelectedFile = recordRTC.getBlob();
$('#uploadForm').append('#attachmentFileId', recordRTC.getBlob());
StartUpload();
});
var FReader;
var Name = "Meeting" + "_" + Date.now() + ".webm";
function StartUpload()
{
FReader = new FileReader();
FReader.onload = function (evnt)
{
socket.emit('Upload', { 'Name': Name, Data: evnt.target.result });
}
socket.emit('Start', { 'Name': Name, 'Size': SelectedFile.size });
}
socket.on('MoreData', function (data)
{
var Place = data['Place'] * 524288; //The Next Blocks Starting Position
var NewFile; //The Variable that will hold the new Block of Data
if (SelectedFile.webkitSlice)
NewFile = SelectedFile.webkitSlice(Place, Place + Math.min(524288, (SelectedFile.size - Place)));
else
NewFile = SelectedFile.slice(Place, Place + Math.min(524288, (SelectedFile.size - Place)));
FReader.readAsBinaryString(NewFile);
});
Server Side Code
I get this from here.
socket.on('Start', function (data) { //data contains the variables that we passed through in the html file
var Name = data['Name'];
Files[Name] = { //Create a new Entry in The Files Variable
FileSize : data['Size'],
Data : "",
Downloaded : 0
}
var Place = 0;
try{
var Stat = fs.statSync('Temp/' + Name);
if(Stat.isFile())
{
Files[Name]['Downloaded'] = Stat.size;
Place = Stat.size / 524288;
}
}
catch(er){} //It's a New File
fs.open("Temp/" + Name, 'a', 0755, function(err, fd){
if(err)
{
console.log(err);
}
else
{
Files[Name]['Handler'] = fd; //We store the file handler so we can write to it later
socket.emit('MoreData', { 'Place' : Place, Percent : 0 });
}
});
});
socket.on('Upload', function (data){
var Name = data['Name'];
Files[Name]['Downloaded'] += data['Data'].length;
Files[Name]['Data'] += data['Data'];
if(Files[Name]['Downloaded'] == Files[Name]['FileSize']) //If File is Fully Uploaded
{
fs.write(Files[Name]['Handler'], Files[Name]['Data'], null, 'Binary', function(err, Writen){
var input = fs.createReadStream("Temp/" + Name);
var output = fs.createWriteStream("Video/" + Name);
//util.pump(readableStream, writableStream, [callback])
//Deprecated: Use readableStream.pipe(writableStream)
input.pipe(output);
input.on("end", function() {
console.log("end");
fs.unlink("Temp/" + Name, function ()
{ //This Deletes The Temporary File
console.log("unlink this file:",Name );
//socket.emit('Done', {'Image' : 'Video/' + Name + '.jpg'});
});
});
});
}
else if(Files[Name]['Data'].length > 10485760){ //If the Data Buffer reaches 10MB
fs.write(Files[Name]['Handler'], Files[Name]['Data'], null, 'Binary', function(err, Writen){
Files[Name]['Data'] = ""; //Reset The Buffer
var Place = Files[Name]['Downloaded'] / 524288;
var Percent = (Files[Name]['Downloaded'] / Files[Name]['FileSize']) * 100;
socket.emit('MoreData', { 'Place' : Place, 'Percent' : Percent});
});
}
else
{
var Place = Files[Name]['Downloaded'] / 524288;
var Percent = (Files[Name]['Downloaded'] / Files[Name]['FileSize']) * 100;
socket.emit('MoreData', { 'Place' : Place, 'Percent' : Percent});
}
});
If both clients are on same machine/system its working fine, but if both clients are on different system then meeting is not recorded.
I'm new with node.js and I'm trying to collaborate in a project adding a mocha test suite for it. The issue that I have at the moment is the following
ReferenceError: Board is not defined
at new Game (/Users/.../dr_mojo/public/javascripts/game.js:8:20)
at Context.<anonymous> (/Users/.../dr_mojo/test/test.game.js:13:17)
at Test.Runnable.run (/usr/local/lib/node_modules/mocha/lib/runnable.js:213:32)
at Runner.runTest (/usr/local/lib/node_modules/mocha/lib/runner.js:343:10)
at Runner.runTests.next (/usr/local/lib/node_modules/mocha/lib/runner.js:389:12)
. . .
when run my test with
$> mocha -u tdd test/test.game.js --reporter spec
public/javascripts/board.js
function Board(width, height) {
this.board = new Array(width);
this.width = width;
this.height = height;
for( var i = 0; i < width ; ++i) {
this.board[i] = new Array(height);
}
}
...
if(typeof module != 'undefined') {
module.exports.Board = Board;
}
public/javascripts/game.js
function Game(lvl, speed, music) {
this.initial = { ... };
this.board = new Board(board_size[0], board_size[1]);
...
}
...
if(typeof module != 'undefined') {
module.exports.Game = Game;
}
test/test.game.js
var assert = require("assert");
var Board = require(__dirname + "/../public/javascripts/board.js").Board;
var Pill = require(__dirname + "/../public/javascripts/pill.js").Pill;
var Game = require(__dirname + "/../public/javascripts/game.js").Game;
describe('Game', function(){
it('Clears a row', function(){
var game = new Game();
var pill1 = new Pill(game.board, game.detector, [ {x : 0 , y : 0 }, {x : 1, y : 0 } ],["red", "red"]);
var pill2 = new Pill(game.board, game.detector, [ {x : 2 , y : 0 }, {x : 3, y : 0 } ],["red", "red"]);
assert.equal(game.board.matches().length, 1);
game.findMatches(function(){});
assert.equal(game.board.matches().length, 0);
})
})
server.js
var express = require('express'),
port = 8888;
var app = express.createServer();
app.use(express.static(__dirname + '/public'));
app.set("view engine", "jade");
app.set('view options', { layout: false });
app.get('/play', function(req, res){
res.render('play_game');
});
app.listen(port);
As you can see the error is in game.js:8 the thing is that I don't know how to configure it properly given that when the game is playing it works ok, this means that new Game() works ok and the problem is that I'm not configuring it properly from the test suite. I'll appreciate any help. Thanks in advance.
From the code you provided my guess is that you'll need to require board.js from game.js like so:
var Board = require(__dirname + "/../public/javascripts/board.js").Board;
It looks like this is a browser game that you're also testing from node.js. Is that correct?