PHP - Web Sockets

 
Vista:

Web Sockets

Publicado por J15loucel (1 intervención) el 15/08/2023 17:22:32
Estoy haciendo un proyecto en el cual quiero ejecutar un fichero .jar de forma asíncrona. Para hacerlo he utilizado esta librería EventDispatcherInterface. El problema que tengo es que no sé cómo notificarle al cliente que ya se terminó de ejecutar el .jar y para ello se me ocurrió utilizar websockets. Empecé por hacer algo básico, el problema es que primero no recibe ningún mensaje de parte del servidor y ahora el cliente se me conecta y desconecta. ¿Alguna idea de porque me puede estar pasando?

Código del cliente js:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// WebSocket setup
const socket = new WebSocket('ws://localhost:8080');
 
socket.addEventListener('open', event => {
    console.log(event);
});
 
 
socket.addEventListener('error', error => {
    console.error('WebSocket error:', error);
  });
 
socket.addEventListener('message', event => {
    const message = JSON.parse(event.data);
    if (message.type === 'progress') {
        console.log(message.text);
    }
});
 
socket.addEventListener('close', event => {
    console.log(event);
});
 
 
// Fetch request
document.getElementById('upload-button').addEventListener('click', () => {
    const fileInput = document.getElementById('zip-file');
 
    const formData = new FormData(); // Create a new FormData object
    formData.append('del-file', fileInput.files[0]); // Append the selected file to the FormData
 
    fetch('/start-process', {
        method: 'POST',
        body: formData, // Send the FormData as the request body
    })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));
});

Código de el controller:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
     * @Route("/start-process", name="start_process", methods={"POST"})
     */
    public function startProcess(Request $request, MessageBusInterface $messageBus, WebSocketServer $webSocketServer): JsonResponse
    {
        // Start the asynchronous background job
        $message = ['type' => 'progress', 'text' => 'Job started'];
        $webSocketServer->broadcast(json_encode($message));
 
        // Simulate background job
        sleep(10); // Simulate work
        $message = ['type' => 'progress', 'text' => 'Job in progress...'];
        $webSocketServer->broadcast(json_encode($message));
        sleep(2); // Simulate work
        // Simulate background job completion
        $message = ['type' => 'progress', 'text' => 'Job completed'];
        $webSocketServer->broadcast(json_encode($message));
 
    return new JsonResponse(['message' => 'Process finished']);

Código del servidor:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php
// src/Command/WebSocketServerCommand.php
 
namespace App\Command;
 
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use App\WebSocket\WebSocketServer;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
 
class WebSocketServerCommand extends Command
{
    // Configure the command
    protected function configure()
    {
        $this
            ->setName('app:java-server')
            ->setDescription('Starts the WebSocket server.');
    }
 
    // Execute the command
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        // Configure and start the WebSocket server
        $server = IoServer::factory(new HttpServer(
            new WsServer(
                // Your WebSocket handler class
                new WebSocketServer()
            )
        ), 8080);
 
        // Run the WebSocket server
        $server->run();
    }
}
 
// Otra clase
<?php
 
namespace App\WebSocket;
 
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
 
class WebSocketServer implements MessageComponentInterface
{
    protected $clients;
 
    public function __construct()
    {
        $this->clients = new \SplObjectStorage();
    }
 
    public function onOpen(ConnectionInterface $conn)
    {
        $this->clients->attach($conn);
        $jsonMessage = json_encode(['type' => 'broadcast', 'message' => $message]);
        $conn->send($jsonMessage);
    }
 
    public function onMessage(ConnectionInterface $from, $message)
    {
        foreach ($this->clients as $client) {
            $client->send($message);
        }
    }
 
    public function onClose(ConnectionInterface $conn)
    {
        $this->clients->detach($conn);
    }
 
    public function onError(ConnectionInterface $conn, \Exception $e)
    {
        $conn->close();
    }
 
    public function broadcast($message)
    {
        $jsonMessage = json_encode(['type' => 'broadcast', 'message' => $message]);
        foreach ($this->clients as $client) {
            $client->send($message);
        }
    }
}
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de Mauro
Val: 2.761
Oro
Ha aumentado 1 puesto en PHP (en relación al último mes)
Gráfica de PHP

Web Sockets

Publicado por Mauro (1036 intervenciones) el 18/08/2023 15:42:49
Hola:

Se me hace un poco complicado evaluar este código sin instalar todo localmente... a simple vista está ok. Tal vez te convenga buscar en logs del servidor si los tienes o utilizar alguna herramienta de debugging para intentar encontrar el punto exacto de falla y, una vez con eso, si continúas con problemas podremos ayudarte desde aquí.

Saludos
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar