Socket.io connection refused - node.js

I'm currently working on a simple game using WebSockets (first time!). However, my console is filled with net::ERR_CONNECTION_REFUSED errors, and I can't get anything to work.
I've been trying to fix the errors for hours and have seen a few other questions online with similar problems, but nothing has worked for me so far.
Here is my code:
server.js:
const { createGameState, gameLoop } = require("./game")
const { FRAME_RATE } = require("./constants")
const io = require("socket.io")(httpServer, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"]
}
});
io.on("connection", client => {
const state = createGameState()
startGameInterval(client, state)
});
function startGameInterval(client, state) {
const intervalId = setInterval(() => {
const winner = gameLoop(state);
console.log("interval");
if(!winner) {
client.emit("gameOver");
clearInterval(intervalId);
} else {
client.emit("gameover");
clearInterval(intervalId);
}
}, 1000 / FRAME_RATE); // 1000
}
io.listen(3000);
index.js (top part):
const backgroundColor = "#1c1315";
const snakeColor = "#7d7778";
const foodColor = "#f55872";
const socket = io("http://localhost:3000")
socket.on("init", handleInit());
// socket.on("gamestate", handleGameState());
const gameScreen = document.getElementById("gameScreen");
let canvas, ctx;
const gameState = {
player: {
pos: {
x: 3,
y: 10,
},
vel: {
x: 1,
y: 0,
},
snake: [
{x: 1, y: 10},
{x: 2, y: 10},
{x: 3, y: 10},
]
},
food: {
x: 7,
y: 7,
},
gridsize: 20,
};
Here is the error that I'm getting; it gets printed in the console every 5 seconds or so.
polling-xhr.js:206 GET http://localhost:3000/socket.io/?EIO=4&transport=polling&t=NW6GI07 net::ERR_CONNECTION_REFUSED
I'm very new to socket.io/websockets in general, so I don't know what this error means or what I could do to fix the issue. Any help would be massively appreciated!

Related

Inconsistent behaviour of mocking DOMPoint in Jest

I have a number of geometry functions that use DOMPoint and DOMRect, which I want to test using jest. The framework is configured to use jsdom as test environment. Unfortunately, jsdom does not have definitions for DOMPoint and DOMRect, hence I need to mock them.
In my setupUnitTests.ts file, which is set as setupFilesAfterEnv value in jest.config.ts I have this mock call:
Object.defineProperty(globalThis, "DOMPoint", {
writable: true,
enumerable: true,
value: jest.fn().mockImplementation((x?: number, y?: number, z?: number, w?: number) => {
return {
x: x ?? 0,
y: y ?? 0,
z: z ?? 0,
w: w ?? 0,
matrixTransform: jest.fn(),
toJSON: jest.fn(),
};
}),
});
const p = new DOMPoint(1, 2, 3, 4);
The call at the end returns a DOM point instance with the expected values, fine.
In my test spec, however, the DOMPoint instance is not initialised. The mock implementation function is not called, like it is when I create a DOM point in the setup file. My spec file is very simple:
import { inflateRect, pointInRect, rectsAreEqual } from "../../../utilities/graphics";
describe("Graphics Tests", () => {
it("Rectangles", () => {
const point1 = new DOMPoint(2, 1, 3, 4);
const point2 = new DOMPoint(-95, 3, 4, 1);
const rect1 = new DOMRect(0, 0, 0, 0);
const rect2 = new DOMRect(-100, 0, 10, 10);
const rect3 = new DOMRect(0, 0, 10, 10);
const rect4 = new DOMRect(0, 0, 10, 10);
const rect5 = new DOMRect(-1, -1, 12, 12);
expect(pointInRect()).toBe(false);
expect(pointInRect(point1)).toBe(false);
expect(pointInRect(point1, rect1)).toBe(false);
expect(pointInRect(point1, rect2)).toBe(false);
expect(pointInRect(point2, rect2)).toBe(true);
expect(rectsAreEqual(rect1, rect2)).toBe(false);
expect(rectsAreEqual(rect3, rect4)).toBe(true);
expect(rectsAreEqual(rect4, rect3)).toBe(true);
expect(inflateRect(rect3, 1, 1, 1, 1)).toStrictEqual(rect5);
});
});
What's missing here? Why is the function given to jest.fn().mockImplementation not called?
The mock itself is definitely used, because when I remove it I get the error about DOMPoint not being defined.
I then moved the mock to the spec file:
describe("Graphics Tests", () => {
Object.defineProperty(global.self, "DOMPoint", {
writable: true,
enumerable: true,
value: jest.fn().mockImplementation((x?: number, y?: number, z?: number, w?: number) => {
return {
x: x ?? 0,
y: y ?? 0,
z: z ?? 0,
w: w ?? 0,
matrixTransform: jest.fn(),
toJSON: jest.fn(),
};
}),
});
it("Rectangles", () => {
const point1 = new DOMPoint(2, 1, 3, 4);
...
});
});
and found the mock function still not being called (but the mock defined). This is pretty confusing...
While debugging through the Jest code to compare the execution paths between the constructor invocations, I saw that in the spec file I had no mock config anymore (the default was used), which ultimately led me to the solution of my problem. In the jest config file I had set resetMocks: true, which caused the mocks to be removed. After setting that to false things started working as expected.

graph doesnt show up in the first time im running the client

im doing a project of crypocurrency site , and ive managed to show up the graph some times , but im facing a problem that my graph wont show up in the first run ,
i think its because i cant get the info at the start correct,and i know that the linechart in the return is making this problem
you got any idea how to fix it?
app.js
function App() {
var [details, setDetails] = useState();
var [details2, setDetails2] = useState();
console.log("!2");
var o = [] // empty Object
var price = 0;
var date = "";
var i = 1;
var array = "";
const [data,setData]=React.useState(null);
const [userData, setUserData] = useState({});
useEffect(() => {
fetch('http://localhost:3002/bitcoin').then((response)=> response.json())
.then((data)=>
{
console.log(data);
var years = data.map(value => value[0]);
var prices1 = data.map(value2 => value2[1]);
console.log(years);
console.log(prices1);
setUserData({
labels: years,
datasets: [
{
label: "Price",
data: prices1,
backgroundColor: [
"rgba(75,192,192,1)",
],
borderColor: "black",
borderWidth: 2,
},
],
});
})
})
return (
<div className="App">
<h1>fedgfdsgs</h1>
<LineChart chartData={userData} />
</div>//the line chart is causing the problem but without it i cant show my graph
);
}
export default App;
linechart.js
function LineChart({ chartData }) {
return <Line data={chartData} />;
}
export default LineChart;
thank u for your time :)

How to run mediapipe facemesh on a ES6 node.js environment alike react

I am trying to run this HTML example https://codepen.io/mediapipe/details/KKgVaPJ from https://google.github.io/mediapipe/solutions/face_mesh#javascript-solution-api in a create react application. I have already done:
npm install of all the facemesh mediapipe packages.
Already replaced the jsdelivr tags with node imports and I got the definitions and functions.
Replaced the video element with react-cam
I don't know how to replace this jsdelivr, maybe is affecting:
const faceMesh = new FaceMesh({
locateFile: (file) => {
return `https://cdn.jsdelivr.net/npm/#mediapipe/face_mesh/${file}`;
}
});
So the question is:
Why the facemesh is not showing? Is there any example of what I am trying to do?
This is my App.js code (sorry for the debugugging scaffolding):
import './App.css';
import React, { useState, useEffect } from "react";
import Webcam from "react-webcam";
import { Camera, CameraOptions } from '#mediapipe/camera_utils'
import {
FaceMesh,
FACEMESH_TESSELATION,
FACEMESH_RIGHT_EYE,
FACEMESH_LEFT_EYE,
FACEMESH_RIGHT_EYEBROW,
FACEMESH_LEFT_EYEBROW,
FACEMESH_FACE_OVAL,
FACEMESH_LIPS
} from '#mediapipe/face_mesh'
import { drawConnectors } from '#mediapipe/drawing_utils'
const videoConstraints = {
width: 1280,
height: 720,
facingMode: "user"
};
function App() {
const webcamRef = React.useRef(null);
const canvasReference = React.useRef(null);
const [cameraReady, setCameraReady] = useState(false);
let canvasCtx
let camera
const videoElement = document.getElementsByClassName('input_video')[0];
// const canvasElement = document.getElementsByClassName('output_canvas')[0];
const canvasElement = document.createElement('canvas');
console.log('canvasElement', canvasElement)
console.log('canvasCtx', canvasCtx)
useEffect(() => {
camera = new Camera(webcamRef.current, {
onFrame: async () => {
console.log('{send}',await faceMesh.send({ image: webcamRef.current.video }));
},
width: 1280,
height: 720
});
canvasCtx = canvasReference.current.getContext('2d');
camera.start();
console.log('canvasReference', canvasReference)
}, [cameraReady]);
function onResults(results) {
console.log('results')
canvasCtx.save();
canvasCtx.clearRect(0, 0, canvasElement.width, canvasElement.height);
canvasCtx.drawImage(
results.image, 0, 0, canvasElement.width, canvasElement.height);
if (results.multiFaceLandmarks) {
for (const landmarks of results.multiFaceLandmarks) {
drawConnectors(canvasCtx, landmarks, FACEMESH_TESSELATION, { color: '#C0C0C070', lineWidth: 1 });
drawConnectors(canvasCtx, landmarks, FACEMESH_RIGHT_EYE, { color: '#FF3030' });
drawConnectors(canvasCtx, landmarks, FACEMESH_RIGHT_EYEBROW, { color: '#FF3030' });
drawConnectors(canvasCtx, landmarks, FACEMESH_LEFT_EYE, { color: '#30FF30' });
drawConnectors(canvasCtx, landmarks, FACEMESH_LEFT_EYEBROW, { color: '#30FF30' });
drawConnectors(canvasCtx, landmarks, FACEMESH_FACE_OVAL, { color: '#E0E0E0' });
drawConnectors(canvasCtx, landmarks, FACEMESH_LIPS, { color: '#E0E0E0' });
}
}
canvasCtx.restore();
}
const faceMesh = new FaceMesh({
locateFile: (file) => {
return `https://cdn.jsdelivr.net/npm/#mediapipe/face_mesh/${file}`;
}
});
faceMesh.setOptions({
selfieMode: true,
maxNumFaces: 1,
minDetectionConfidence: 0.5,
minTrackingConfidence: 0.5
});
faceMesh.onResults(onResults);
// const camera = new Camera(webcamRef.current, {
// onFrame: async () => {
// await faceMesh.send({ image: videoElement });
// },
// width: 1280,
// height: 720
// });
// camera.start();
return (
<div className="App">
<Webcam
audio={false}
height={720}
ref={webcamRef}
screenshotFormat="image/jpeg"
width={1280}
videoConstraints={videoConstraints}
onUserMedia={() => {
console.log('webcamRef.current', webcamRef.current);
// navigator.mediaDevices
// .getUserMedia({ video: true })
// .then(stream => webcamRef.current.srcObject = stream)
// .catch(console.log);
setCameraReady(true)
}}
/>
<canvas
ref={canvasReference}
style={{
position: "absolute",
marginLeft: "auto",
marginRight: "auto",
left: 0,
right: 0,
textAlign: "center",
zindex: 9,
width: 1280,
height: 720,
}}
/>
</div >
);
}
export default App;
You don't have to replace the jsdelivr, that piece of code is fine; also I think you need to reorder your code a little bit:
You should put the faceMesh initialization inside the useEffect, with [] as parameter; therefore, the algorithm will start when the page is rendered for the first time
Also, you don't need to get videoElement and canvasElement with doc.*, because you already have some refs defined
An example of code:
useEffect(() => {
const faceMesh = new FaceDetection({
locateFile: (file) => {
return `https://cdn.jsdelivr.net/npm/#mediapipe/face_detection/${file}`;
},
});
faceMesh.setOptions({
maxNumFaces: 1,
minDetectionConfidence: 0.5,
minTrackingConfidence: 0.5,
});
faceMesh.onResults(onResults);
if (
typeof webcamRef.current !== "undefined" &&
webcamRef.current !== null
) {
camera = new Camera(webcamRef.current.video, {
onFrame: async () => {
await faceMesh.send({ image: webcamRef.current.video });
},
width: 1280,
height: 720,
});
camera.start();
}
}, []);
Finally, in the onResults callback I would suggest printing first the results, just to check if the Mediapipe implementation is working fine. And don't forget to set the canvas size before drawing something.
function onResults(results){
console.log(results)
canvasCtx = canvasReference.current.getContext('2d')
canvas.width = webcamRef.current.video.videoWidth;
canvas.height = webcamRef.current.video.videoHeight;;
...
}
Good luck! :)

Code for a platform moving back and Forth

I'am trying to make a game where the character can jump on a platform that's moving Horizontally, once the platform reaches a specific point it comes back and it repeats. However I have had some trouble finding the correct way to write the code for this I tried using setVelocityX() is looks like this
var movingPlatform = {
moveRight : function(){
platforms.setVelocityX(100)
},
moveleft : function(){
platforms.setVelocityX(-100);
}
}
var move = true;
if(move = true){
movingPlatform.moveRight()
}
if(move = false){
movingPlatform.moveleft();
}
if(platforms.x <= platformMinX){
move = true;
}
if(platforms.x >= platformMaxX){
move = false;
}
all this did was when the platform reaches the 'platformMaxX' point it just moved back and forth in that area so 'movingPlatform.moveRight()' is still being called
var config = {
type: Phaser.AUTO,
parent: 'phaser-example',
width: 800,
height: 600, loader: {
baseURL: 'https://raw.githubusercontent.com/nazimboudeffa/assets/master/',
crossOrigin: 'anonymous'
},
scene: {
preload: preload,
create: create,
update: update
},
physics: {
default: 'arcade'
}
};
var game = new Phaser.Game(config);
var dude;
var alien1, alien2;
var direction = 1
function preload ()
{
this.load.image('dude', 'sprites/phaser-dude.png');
this.load.image('alien1', 'sprites/phaser-alien.png');
this.load.image('alien2', 'sprites/alien2.png');
}
function create ()
{ dude = this.physics.add.sprite(300, 100, 'dude');
alien1 = this.physics.add.sprite(400, 100, 'alien1');
alien1.body.immovable = true;
alien2 = this.physics.add.sprite(100, 100, 'alien2');
alien2.body.immovable = true;
}
function update ()
{
this.physics.add.collider(dude, alien1, flipX, null, this);
this.physics.add.collider(dude, alien2, flipX, null, this);
dude.setVelocityX(direction * 100)
}
function flipX ()
{
direction = - direction
}
<script src="//cdn.jsdelivr.net/npm/phaser#3.18.1/dist/phaser.min.js"></script>
var config = {
type: Phaser.AUTO,
parent: 'phaser-example',
width: 800,
height: 600, loader: {
baseURL: 'https://raw.githubusercontent.com/nazimboudeffa/assets/master/',
crossOrigin: 'anonymous'
},
scene: {
preload: preload,
create: create
},
physics: {
default: 'arcade'
}
};
var game = new Phaser.Game(config);
function preload ()
{
this.load.image('dude', 'sprites/phaser-dude.png');
}
function create ()
{
this.dude = this.physics.add.sprite(100, 100, 'dude');
const tween = this.tweens.add({
targets: this.dude,
x: 300,
ease: 'Power0',
duration: 3000,
flipX: true,
yoyo: true,
repeat: -1,
});
}
<script src="//cdn.jsdelivr.net/npm/phaser#3.19.0/dist/phaser.js"></script>

vue mutation push object reference?

addSentence: (state) => {
const obj = state;
// next line is correct;
obj.sentences.push({ ...obj.current });
// change to next line, get error
// obj.sentences.push(obj.current);
obj.current = new Sentence();
},
import Constants from './Constants';
export default class Sentence {
constructor(config) {
this.text = '';
this.fontFamily = 'KaiTi';
this.fontSize = 16;
this.fontStyle = '';
this.appearStyle = {
name: 'type',
speed: 40,
startDelay: 0,
};
this.disappearStyle = {
name: 'backspace',
speed: 80,
startDelay: 0,
smartBackspace: true,
};
}
play(context) {
}
drawText() {
}
}
state.cuurent is an object of type Sentence.
And state.sentences = [Sentence]
This is a mutation handler.
Error:
[vuex] Do not mutate vuex store state outside mutation handlers.

Resources