rewrite with wss

This commit is contained in:
leca 2023-08-02 19:47:27 +03:00
parent 576a88765f
commit 0a183effc4
8 changed files with 978 additions and 113 deletions

19
cert.pem Normal file
View File

@ -0,0 +1,19 @@
-----BEGIN CERTIFICATE-----
MIIDIzCCAgsCFGL2RUvaMPh1oocuvA2JvX8zFCx0MA0GCSqGSIb3DQEBCwUAME0x
CzAJBgNVBAYTAlJVMRMwEQYDVQQIDApTb21lLVN0YXRlMRAwDgYDVQQKDAdmb3hh
cm15MRcwFQYDVQQDDA5wYi5mb3hhcm15Lm9yZzAgFw0yMzA4MDIwOTUwMjBaGA8y
MDUwMTIxNzA5NTAyMFowTTELMAkGA1UEBhMCUlUxEzARBgNVBAgMClNvbWUtU3Rh
dGUxEDAOBgNVBAoMB2ZveGFybXkxFzAVBgNVBAMMDnBiLmZveGFybXkub3JnMIIB
IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxiIKOr4RqIwK+2dpazzTirDp
333FdmTTxvTs5R6jaTNEL0MfZNKi0rmxUZEBSiOTJJ/5tw8APW86JmtajvujHKFb
MdFXUPHew9a9QqWX3k+yu5xc2x4Xz+xJTkHLVkrcAWtI1U6RdZBap04DUNVkqm5g
30BtSSbGdrcO1LT6cjvKIcw6xQNhmobWZx72/c9+4RFPsdF6FlTsBblL7s/swTmg
l5srA7jbOywLM8U2o8iVRh3sVXokJ0XKlRKfkpWEZRvuWr0j0g79evc8X3YLr7qk
1GJViO4IJwRDqcvlSlBMVS3rdegqc+ijap4sd/AGsCMWUoSQiDrnKWEfIvWCTwID
AQABMA0GCSqGSIb3DQEBCwUAA4IBAQB4aJl7OH8brVKlywY3wfLASFpeodM11+vH
3Y1FVx03vDuS055FRCMbwq/MAswXkflQsxyx6gatpbiWoxYJpSzuUyttwMZZ0oHf
FawDJGvYBQHYDsRgneXv4s2NrRtNQpi/+Fg9Qti5vqZzJ9y6wUKUJwFIN+ksM6p6
C4gtjokWHpC19qRwN1Q+5Kfs1jEYNNnZoFF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08oo3b/VgwmYEVUddGz8C+iinZhY1QPD3p9v8PY=
-----END CERTIFICATE REQUEST-----

View File

@ -1,6 +1,6 @@
var serverAddress = document.getElementById("server-address").value; var serverAddress = document.getElementById("server-address").value;
var serverPort = document.getElementById("server-port").value var serverPort = document.getElementById("server-port").value
var socket = new WebSocket(`ws://${serverAddress}:${serverPort}`); var socket//new WebSocket(`wss://${serverAddress}:${serverPort}`);
var canvas = document.getElementById("board"); var canvas = document.getElementById("board");
var colorInput = document.getElementById("color"); var colorInput = document.getElementById("color");
@ -26,11 +26,12 @@ function drawTimer() {
} }
function connect() { function connect() {
socket.close(); // socket.close();
serverAddress = document.getElementById("server-address").value; serverAddress = document.getElementById("server-address").value;
serverPort = document.getElementById("server-port").value serverPort = document.getElementById("server-port").value
console.log(`Connecting ${serverAddress}:${serverPort}`) console.log(`Connecting ${serverAddress}:${serverPort}`)
socket = new WebSocket(`ws://${serverAddress}:${serverPort}`) socket = new WebSocket(`wss://${serverAddress}:${serverPort}`)
// socket = new WebSocket(`wss://127.0.0.1:8080`)
timer.textContent="Board is loading, please wait"; timer.textContent="Board is loading, please wait";
socket.addEventListener("open", (event) => { socket.addEventListener("open", (event) => {
socket.send("{\"code\":0}"); socket.send("{\"code\":0}");

28
key.pem Normal file
View File

@ -0,0 +1,28 @@
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDGIgo6vhGojAr7
Z2lrPNOKsOnffcV2ZNPG9OzlHqNpM0QvQx9k0qLSubFRkQFKI5Mkn/m3DwA9bzom
a1qO+6McoVsx0VdQ8d7D1r1CpZfeT7K7nFzbHhfP7ElOQctWStwBa0jVTpF1kFqn
TgNQ1WSqbmDfQG1JJsZ2tw7UtPpyO8ohzDrFA2GahtZnHvb9z37hEU+x0XoWVOwF
uUvuz+zBOaCXmysDuNs7LAszxTajyJVGHexVeiQnRcqVEp+SlYRlG+5avSPSDv16
9zxfdguvuqTUYlWI7ggnB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kMJl+vjZtN3Qjk
mIosb3bphspaB7MR3wfPwHl+NGmflhO72wyL2CaHAoGAYAWC1yK90C/E79qA+I2A
HH4sqOB5NeoOvzJXfLhsDhKwajmpH/h5hfDSJ4XH7WoL0rcVkzZKoEWMeO3mfrUS
kWNIA368Gki9dfyJgQx2ewODcZiLWI6kzQ1XbeCUsyI2ALfm3CTft6pg5lifCwty
ItDNyjbaR8CSIFcsKwaebdI=
-----END PRIVATE KEY-----

788
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -24,6 +24,7 @@
"jimp": "^0.22.10", "jimp": "^0.22.10",
"nodemon": "^3.0.1", "nodemon": "^3.0.1",
"pug": "^3.0.2", "pug": "^3.0.2",
"ws": "^8.13.0" "ws": "^8.13.0",
"wss": "^3.3.4"
} }
} }

View File

@ -1,9 +1,8 @@
{ {
"appPort": 7865,
"httpPort": 8080, "httpPort": 8080,
"boardWidth": 1920, "boardWidth": 1920,
"boardHeight": 1080, "boardHeight": 1080,
"serverAddress": "foxarmy.org", "serverAddress": "127.0.0.1",
"saveFile": "../board.png", "saveFile": "./board.png",
"timeBetweenPixels": 5 "timeBetweenPixels": 5
} }

View File

@ -1,22 +1,27 @@
const WebSocket = require('wss'); const WebSocket = require('ws');
const express = require('express');
const http = express();
const path = require('path'); const path = require('path');
const pug = require('pug'); const pug = require('pug');
const Jimp = require('jimp'); const Jimp = require('jimp');
const fs = require('fs'); const fs = require('fs');
const https = require('https');
const http = require('http');
const express = require('express');
const app = express();
http.use(express.static(path.join(__dirname, '../html'))); app.use(express.static(path.join(__dirname, '../html')));
http.set('view engine', 'pug'); app.set('view engine', 'pug');
const config = require("../settings.json"); const config = require("../settings.json");
const httpPort = config.httpPort; const httpPort = config.httpPort;
const appPort = config.appPort;
const serverAddress = config.serverAddress; const serverAddress = config.serverAddress;
const saveFile = config.saveFile; const saveFile = config.saveFile;
const boardWidth = config.boardWidth; const boardWidth = config.boardWidth;
const boardHeight = config.boardHeight; const boardHeight = config.boardHeight;
const timeBetweenPixels = config.timeBetweenPixels; const timeBetweenPixels = config.timeBetweenPixels;
const credentails = {
key: fs.readFileSync("key.pem"),
cert: fs.readFileSync("cert.pem")
}
var toQuit = false; var toQuit = false;
@ -25,12 +30,11 @@ var board = new Array(boardWidth * boardHeight * 4);
if (!fs.existsSync(saveFile)) { if (!fs.existsSync(saveFile)) {
console.log("No save file found, creating blank board."); console.log("No save file found, creating blank board.");
board.fill(255); board.fill(255);
let image = new Jimp(boardWidth, boardHeight, save);
} else { } else {
console.log("Save file found, loading") console.log("Save file found, loading")
let image = Jimp.read(`./${saveFile}`, (err, image) => { let image = Jimp.read(`./${saveFile}`, (err, image) => {
for (let x = 0; x < boardWidth; x ++) { for (let x = 0; x < boardWidth; x++) {
for (let y = 0; y < boardHeight; y ++) { for (let y = 0; y < boardHeight; y++) {
pixelNumber = evaulatePixelNumber(x * 4, y * 4); pixelNumber = evaulatePixelNumber(x * 4, y * 4);
let pixel = Jimp.intToRGBA(image.getPixelColor(x, y)) let pixel = Jimp.intToRGBA(image.getPixelColor(x, y))
board[pixelNumber + 0] = pixel.r board[pixelNumber + 0] = pixel.r
@ -44,24 +48,33 @@ if (!fs.existsSync(saveFile)) {
} }
const ws = new WebSocket.Server({ const httpsServer = https
port: appPort, .createServer(
credentails,
app
)
.listen(httpPort, "0.0.0.0", () => {
console.log("test))0");
// const ws = new WebSocket(`wss://127.0.0.1:${httpPort}`, {
// rejectUnauthorized: false
// });
// ws.on('error', console.error);
// ws.on('message', (msg) => {
// console.log("Client got a message: ", msg.toString())
// })
// ws.on('open', function open() {
// ws.send('All glory to WebSockets!');
// });
})
const server = new WebSocket.Server({
server: httpsServer,
host: "0.0.0.0", host: "0.0.0.0",
handleProtocols: true,
server: httpsServer
// AddressInfo.family = 4;
// server: true
}); });
// var ws = require('ws').Server;
// const server = new ws({})
console.log(server)
// const server = new WebSocket.Server({ http });
let clients = []; let clients = [];
let lastPixelTimestamp = []; let lastPixelTimestamp = [];
const evaulatePixelNumber = (x, y) => { const evaulatePixelNumber = (x, y) => {
let pixelNumber; let pixelNumber;
if (y > 0) if (y > 0)
@ -70,21 +83,20 @@ const evaulatePixelNumber = (x, y) => {
pixelNumber = x; pixelNumber = x;
return pixelNumber; return pixelNumber;
} }
server.on('connection', (client) => {
server.on('connection', function(client) {
console.log(`New client has connected, assigning id ${clients.length} to it.`)
client.id = clients.length; client.id = clients.length;
clients.push(client); clients.push(client);
console.log(`New client has connected, assigning id ${clients.length} to it.`)
client.on('message', function(msg) { client.on('message', function (msg) {
let packet, content, code; let packet, content, code;
try { try {
packet = JSON.parse(msg.toString()); packet = JSON.parse(msg.toString());
content = packet.content; content = packet.content;
code = packet.code; code = packet.code;
} catch (e) {console.log(e)} } catch (e) { console.log(e) }
let response = {}; let response = {};
switch(code) { switch (code) {
case 0: case 0:
response.code = 0; response.code = 0;
response.content = board; response.content = board;
@ -99,17 +111,16 @@ server.on('connection', function(client) {
let pixelNumber = evaulatePixelNumber(contentJson.x * 4, contentJson.y * 4); let pixelNumber = evaulatePixelNumber(contentJson.x * 4, contentJson.y * 4);
if (contentJson.x < 0 || contentJson.y < 0) client.send("{\"code\":-1}"); if (contentJson.x < 0 || contentJson.y < 0) client.send("{\"code\":-1}");
let unixTime = Math.floor(new Date().getTime() / 1000);
if (lastPixelTimestamp[client.id] == undefined || unixTime - lastPixelTimestamp[client.id] > timeBetweenPixels - 1) {
lastPixelTimestamp[client.id] = unixTime;
for (let i = 0; i < clients.length; i++) {
response.pixelOwner = i == client.id ? true : false;
clients[i].send(Buffer.from(JSON.stringify(response)));
board[pixelNumber + 0] = contentJson.r; board[pixelNumber + 0] = contentJson.r;
board[pixelNumber + 1] = contentJson.g; board[pixelNumber + 1] = contentJson.g;
board[pixelNumber + 2] = contentJson.b; board[pixelNumber + 2] = contentJson.b;
board[pixelNumber + 3] = 255; board[pixelNumber + 3] = 255;
let unixTime = Math.floor(new Date().getTime() / 1000);
if (lastPixelTimestamp[client.id] == undefined || unixTime - lastPixelTimestamp[client.id] > timeBetweenPixels - 1) {
lastPixelTimestamp[client.id] = unixTime;
for (let i = 0; i < clients.length; i ++) {
response.pixelOwner = i == client.id? true : false;
clients[i].send(Buffer.from(JSON.stringify(response)));
} }
// clients.forEach(c => c.send(Buffer.from(JSON.stringify(response)))); // clients.forEach(c => c.send(Buffer.from(JSON.stringify(response))));
// client.send("{\"code\":2}") // client.send("{\"code\":2}")
@ -123,25 +134,30 @@ server.on('connection', function(client) {
} }
}); });
client.on('close', function() { client.on('close', function () {
clients = clients.filter(s => s !== client); clients = clients.filter(s => s !== client);
}); });
}); });
http.get('/', (req, res) => {
res.render('index.pug', {root: __dirname, server: serverAddress, port:appPort});
})
http.listen(httpPort, "0.0.0.0", () => {
console.log(`Starting pixelbattle http server on port ${httpPort}`);
app.get('/', (req, res) => {
// res.send("Hello")
res.render('index.pug', { root: __dirname, server: serverAddress, port: httpPort });
}) })
app.use(function (err, req, res, next) {
if (err) console.log(err);
next();
});
const save = (err, image) => { const save = (err, image) => {
if (err) throw err; if (err) throw err;
console.log() console.log()
for (let x = 0; x < boardWidth; x ++) { for (let x = 0; x < boardWidth; x++) {
for (let y = 0; y < boardHeight; y ++) { for (let y = 0; y < boardHeight; y++) {
let pixelNumber = evaulatePixelNumber(x * 4 , y * 4); let pixelNumber = evaulatePixelNumber(x * 4, y * 4);
image.setPixelColor( image.setPixelColor(
Jimp.rgbaToInt( Jimp.rgbaToInt(
Number(board[pixelNumber + 0]), Number(board[pixelNumber + 0]),
@ -177,4 +193,3 @@ process.on('SIGINT', () => {
toQuit = true; toQuit = true;
let image = new Jimp(boardWidth, boardHeight, save); let image = new Jimp(boardWidth, boardHeight, save);
}); });