简体   繁体   中英

Non blocking input prompt? node.js

I am working on a chat app using socket.io/node.js, in the terminal,I am able to chat with another session, but when I send a message to in order to read the message I have the either hit enter on the prompt, or type a message, not the best. Any alternatives to console.log()?

The console.log containing the nick and message variables, is fired when the new message event is received, any alternatives to make it more realtime? I am using the Prompt-Sync module.

EDIT: on message event snippet.

On message function:

        socket.on('msg',function(data){ 

         var newmessage = data.m;
         var newmsgnick = data.nick;
         newmessagefunc(newmessage,newmsgnick)

        });

newmessagefunc function:

        function newmessagefunc(message,nick){
         console.log(nick+": "+message);
         message = i("message: ")
            }

The message log:

 message: Hello - how goes?
 Ozzie: Hello - how goes?
 message: Hello - ?
 Ozzie: it goes well. 
 message: 

To read the message the other user sent, I have to either submit a message, or just enter on the message prompt, they do not show as they are sent, as socket.io is said to be able to do, any ways around this?

You are reading a message when there is an incoming message. This is forcing you to type a message before you display the incoming message.

socket.on('msg',function(data){ 
  var newmessage = data.nm;
  var newmsgnick = data.nn;
  console.log(newmessage);
});

Now, this will print the incoming message. Keep the prompt code outside of this block.

while(typeof message === "undefined"){
  message = i("message: ") 
}
socket.emit('msg', {'nm':message, 'nn':'nick'});

The native prompt dialog is blocking. Meaning the rest of the script, even when new events are received, will not run until it is unblocked.

Most will use a textbox to get user input, and on a button click or similar event to grab the input and post the message. This way the socket msg event can be triggered without it being blocked

HTML

<input id="message"><button id="sendmsgbtn">Send</button>

JS

var msgInput = document.getElementById("message");
var btn = document.getElementById("sendmsgbtn");

btn.addEventListener("click,sendMessage);
msgInput.addEventListener("keyup",function(e){
    //this is used to detect if there was a enter 
    //key press inside the input
    if(e.keyCode==13){
        sendMessage();
    }
});

socket.on('msg',onMsg);    

function onMsg(data){
    var newmessage = data.nm;
    var newmsgnick = data.nn;
    console.log(newmessage);
    //add message to chat window
}

function sendMsg(){
    var msg = msgInput.value;
    msgInput.value = "";
    socket.emit("msg",{msg:msg});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM