Bonjour

J'essaye actuelement de crée un chats en temps réels pour mes users en utilisants socket.io , hors j'ai mes messages qui s'insere bien en bdd mais quand je submit rien en s'affiche en temps réelles , donc je doit actualiser.

Quand je submit dans la console j'ai cela : " 2:469 POST http://127.0.0.1:8000/game/2/chat 500 (Internal Server Error) "
Mon server.js à la racine de mon projet

const io = require('socket.io')(3000, {
    cors: {
        origin: "http://127.0.0.1:8000",
        methods: ["GET", "POST"],
        allowedHeaders: ["Content-Type"],
        credentials: true
    }
});

io.on('connection', (socket) => {
    console.log('a user connected');

    socket.on('chat message', (msg) => {
        console.log('Received message:', msg);
        io.emit('chat message', msg);
    });

    socket.on('disconnect', () => {
        console.log('user disconnected');
    });
});

La function de mon controlleur :

  • J'ai bien Connected to Socket.io server dans la console
  • J'ai getUsername qui m'alerte en " Undefined method 'getUsername' " alors que je l'ai biens dans mon entity.
  • Meme le systeme d'erreur ne s'affcihe pas.
#[Route('/game/{id}/chat', name: 'game_chat', methods: ['POST'])]
    public function chat(Game $game, Request $request, EntityManagerInterface $em, HttpClientInterface $httpClient, LoggerInterface $logger): Response
    {
        $messageContent = $request->request->get('message');

        if (empty($messageContent)) {
            $logger->error('Message content is empty.');
            return new Response('Message content is required.', Response::HTTP_BAD_REQUEST);
        }

        $chatMessage = new Chat();
        $chatMessage->setParticipant($this->getUser());
        $chatMessage->setMessage($messageContent);
        $chatMessage->setGame($game);
        $chatMessage->setTimestamp(new \DateTime());

        $em->persist($chatMessage);
        $em->flush();

        try {
            $response = $httpClient->request('POST', 'http://localhost:3000', [
                'json' => [
                    'username' => $this->getUser()->getUsername(),
                    'message' => $messageContent,
                    'timestamp' => $chatMessage->getTimestamp()->format('d/m/Y H:i'),
                ],
            ]);

            if ($response->getStatusCode() !== 200) {
                $logger->error('Failed to send message to Socket.io server: ' . $response->getContent(false));
                throw new \Exception('Failed to send message to Socket.io server');
            }

        } catch (\Exception $e) {
            // Log l'erreur
            $logger->error('Error sending message to Socket.io server: ' . $e->getMessage());
            return new Response('Error sending message to Socket.io server: ' . $e->getMessage(), Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        return new Response(null, Response::HTTP_NO_CONTENT);
    }

Et ma vue templates/game/chat.html.twig

{# DEBUT  HTML  #}

<h2>Chat de la partie</h2>
<div id="chat-messages">
    {% for chatMessage in game.getChatMessages %}
        <div>
            <strong>{{ chatMessage.getParticipant().getUsername }}</strong>:
            <p>{{ chatMessage.getMessage() }}</p>
            <small>{{ chatMessage.getTimestamp().format('d/m/Y H:i') }}</small>
        </div>
    {% endfor %}
</div>

<form id="chat-form" action="{{ path('game_chat', { 'id': game.id }) }}" method="post">
    <textarea name="message" rows="3"></textarea>
    <button type="submit">Envoyer</button>
</form>

{# fIN  HTML  #}

<script src="https://cdn.socket.io/4.0.0/socket.io.min.js"></script>

<script>
    const socket = io('http://localhost:3000');

    socket.on('connect', function () {
        console.log('Connected to Socket.io server');
    });

    socket.on('disconnect', function () {
        console.log('Disconnected from Socket.io server');
    });

    document.getElementById('chat-form').addEventListener('submit', function (e) {
        e.preventDefault();

        const message = this.message.value;

        fetch(this.action, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: new URLSearchParams(new FormData(this))
        });

        this.message.value = '';
    });

    socket.on('chat message', function (msg) {
        console.log('New message received:', msg);
        const chatMessages = document.getElementById('chat-messages');
        const messageDiv = document.createElement('div');
        messageDiv.innerHTML = `<strong>${msg.username}</strong>:<p>${msg.message}</p><small>${msg.timestamp}</small>`;
        chatMessages.appendChild(messageDiv);
    });
</script>

Aucune réponse