I've installed node.js on my computer and I've successfully tested this code on my computer with two opened web browsers.
The problem is, that the code is not working on the web server. I really don't why?
The codes are from this YouTube playlist: 12: Web Sockets and p5.js Tutorial
index.html
<html>
<head>
<meta charset="UTF-8">
<title>Sockets Example 1</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
<script language="javascript" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.min.js"></script>
<script language="javascript" type="text/javascript" src="sketch.js"></script>
</head>
<body>
</body>
</html>
sketch.js
var socket;
function setup() {
createCanvas(200,200);
background(51);
//socket = io.connect('http://127.0.0.1:3000'); ?
socket = io.connect('http://localhost:3000');
socket.on('mouse', newDrawing);
}
function newDrawing(data) {
noStroke();
fill(255, 0, 100);
ellipse(data.x, data.y, 36, 36);
}
function mouseDragged() {
console.log('Sending: ' + mouseX + ',' + mouseY);
var data = {
x: mouseX,
y: mouseY
}
socket.emit('mouse', data);
noStroke();
fill(255);
ellipse(mouseX, mouseY, 36, 36);
}
server.js
var express = require('express');
var app = express();
var server = app.listen(3000);
app.use(express.static('public'));
console.log("My socket server is running!");
var socket = require('socket.io');
var io = socket(server);
io.sockets.on('connection', newConnection);
function newConnection(socket) {
console.log('new connection: ' + socket.id);
socket.on('mouse', mouseMsg);
function mouseMsg(data) {
socket.broadcast.emit('mouse', data);
}
}
package.json
{
"name": "sockets_example_1",
"version": "1.0.0",
"description": "sockets example 1",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"keywords": [
"sockets",
"p5.js",
"node"
],
"author": "Noa",
"license": "No license",
"dependencies": {
"express": "^4.17.1",
"socket.io": "^2.2.0"
}
}
This is the folder structure:
├───node_modules
│ └───... (created files with node.js on my computer)
├───public
│ ├───index.html
│ └───sketch.js
├───package.json
├───package-lock.json
└───server.js
In chrome web browser I get this error message:
index.js:83 GET http://localhost:3000/socket.io/?EIO=3&transport=polling&t=MqfwDDZ net::ERR_CONNECTION_REFUSED
In firefox web browser I get this error message:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/socket.io/?EIO=3&transport=polling&t=MqfvjtX. (Reason: CORS request did not succeed).
On my web server node.js is installed.