It's the first time I'm working with websockets in Django and I'm not doing it very well, what's happening to me is that I get either the 404 not found error or the error: unexpected server response: 200, I've been checking some tutorials and also reading the documentation and some say to use typeScript but I don't really understand why
Objective
My goal is to be able to make a request to Electron so it can take a print-screen of your user's screen and send it to me as a string so I can manipulate it in Django Python, this part is already functional, I tested it with Simple WebSockets Client
, but now that I'm trying to test with other users and get their screenshot, and for that I'm using ngrok
to keep the server up for other users to access. What happens is that I capture my electronic server and not the other's my users, and now I'm going to try to change the Routes to capture theirs but I'm not succeeding, if anyone can help a lot
index.js
const { desktopCapturer, screen, BrowserWindow, app } = require('electron');
const { spawn } = require('child_process');
const django = spawn('python', ['manage.py', 'runserver']);
const wss = new WebSocket.Server({ port: 8000 });
wss.on('connection', ws => {
ws.on('message', message => {
console.log('Mensagem recebida:', message.toString());
if (message.toString() === 'screenshot_requested') {
captureScreenshots(ws);
}
});
});
function createWindow() {
// Create the browser window
const mainWindow = new BrowserWindow({
title: 'SketchPixel Facial Recognition',
width: 1920,
height: 1680,
icon: 'templates/static/assets/sketchpixel_logo.jpg'
});
// Carregar a URL do aplicativo
const appUrl = 'https://35f8-2001-8a0-ff62-e300-d469-e0a-17a0-b9bd.ngrok-free.app/';
mainWindow.loadURL(appUrl);
// Definir a janela para ser fullscreen
}
django.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
}
);
django.stderr.on('data', (data) => {
console.error(`stderr: ${data}`);
}
);
django.on('close', (code) => {
console.log(`child process exited with code ${code}`);
}
);
Consumers.py
from channels.generic.websocket import AsyncWebsocketConsumer
import json
class ScreenshotConsumer(AsyncWebsocketConsumer):
async def connect(self):
await self.accept()
async def disconnect(self, close_code):
pass
async def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
await self.send(text_data=json.dumps({
'message': message
}))
## Routing.py ##
from django.urls import re_path
from . import consumers
websocket_urlpatterns = [
re_path(r'ws/main/', consumers.ScreenshotConsumer.as_asgi()),
]
views.py
def call_node_script(request): #Função para chamar o script Node.js
print("Solicitando captura de tela...")
ws = websocket.create_connection('wss://35f8-2001-8a0-ff62-e300-d469-e0a-17a0-b9bd.ngrok-free.app/ws/main/')
print("Conexão WebSocket estabelecida com sucesso.")
ws.send('screenshot_requested')
# Receber a resposta do servidor
result = ws.recv()
ws.close()
print("Resposta Recebida com sucesso.")
return result
asgi.py
import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from django.urls import re_path
from main import consumers
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'facial.settings')
websocket_urlpatterns = [
re_path(r'ws/screenshot/', consumers.ScreenshotConsumer.as_asgi()),
]
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter(
websocket_urlpatterns
)
),
# Just HTTP for now. (We can add other protocols later.)
})
Terminal Django
Handshake status 200 OK -+-+-
Handshake status 404 Not Found -+-+-
Electron
update Required