Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

186
Visualizações
Print array in node js server

Hi I have a website from witch I can send a message to node js server and there the message is saved in a a array. When a new message is sent to the server the old message in the array is overwritten by the new message. The array has to contain new and old messages. The output of console after sending message

const http = require('http');
const { Socket } = require('socket.io');
const WebSocketServer = require('websocket').server;
var steviloSporocil = 0;
const sporocila=[];

const server = http.createServer();
console.log('Server is on port 3000')
server.listen(3000);

const wsServer = new WebSocketServer({
    httpServer: server
});

wsServer.on('request', function(request) {
    const connection = request.accept(null, request.origin);

    connection.on('message', function(message) {
        sporocila[steviloSporocil]=[message.utf8Data];
        steviloSporocil++;
        for (let i = 0; i < steviloSporocil; i++) {
            connection.sendUTF(sporocila[i]);
            console.log('Received Message:', sporocila[i]);
        }

    });

    connection.on('close', function(reasonCode, description) {
        console.log('Client has disconnected.');
    });
});
<?php ob_start() ?>
    <?php $titel="Chat"; ?>

    <div class="chat-main" id="text"></div>

    <form name='form' method='post' class="form">
        <div class="form-group">
            <input type="text" class="form-control" id="textbox" name="chat" placeholder="Chat">
            <button type="button" class="btn btn-primary" name="gumb" id="gumb" onclick="Poslji()" autocomplete="off">Send</button>
        </div>
        </form>
        <script>
            function Poslji(){
                const ws = new WebSocket('ws://localhost:3000'); 
                ws.onopen = function() {
                    console.log('WebSocket Client Connected');
                    ws.send(document.getElementById('textbox').value);
                };
            
                ws.onmessage = function(e) {
                    console.log("Received: '" + e.data + "'");
                    document.getElementById('text').innerHTML=e.data;
                };   
            }
    </script>
<?php 
    $content=ob_get_clean();
    require "layout.html.php";
?>

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

If I understood everything, here how to solve your problem: you take all previous message at the specified index and add the new one at the end. If you want to add it at the top, then just invert the two lines.

sporocila[steviloSporocil] = [
  ...sporocila[steviloSporocil],
  message.utf8Data
];
about 4 years ago · Juan Pablo Isaza Relatório

0

You are sending the messages in the array to the client separately using a for-loop and connection.sendUTF(sporocila[i]); and then displaying the last message received using document.getElementById('text').innerHTML=e.data;.

Are you suprised then that your website only shows the last item in the array?

Why not send the entire array using JSON.stringify and then JSON.parse on the client?

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda