Hi Joe_Ward,
I fixed this issue. Thank you so much!
However, do we need to define a server like var WebSocket = require('ws').Server
?
Because, when I defined my server like this:
var WebSocket = require('ws');
var ws = new WebSocket('ws://127.0.0.1:6437');
ws.on('open', function open(){
console.log('connected');
ws.send(Date.now().toString(), {mask: true});
});
ws.on('close', function close() {
console.log('disconnected');
});
ws.on('message', function(data, flags) {
console.log(data);
setTimeout(function timeout() {
ws.send(Date.now().toString(), {mask: true});
}, 500);
});
It is still unable to send or receive any messages from client. It seems client doesn't connect to server yet. I don't know why.
Here is my client.html:
function init1() {
var nickname = prompt("Choose a nickname");
if (nickname) {
connection = new WebSocket("ws://127.0.0.1:6437");
connection.onopen = function(){
console.log("Connection opened successfully!");
connection.send(nickname);
};
connection.onclose = function(){
console.log('Connection closed.');
};
connection.onerror = function(){
console.log('Connection error.');
};
connection.onmessage = function(event){
console.log('onmessage data: ' + event.data);
var div = document.createElement("div");
div.textContent = event.data;
document.body.appendChild(div);
}
}
}
I can run client.html
separately with server (node server.js
) and get the data frame successfully. At the meanwhile, when I run server (node server.js
), it prints out the frame data in the console. Both frame data printed out in client.html
and console log are the same. Plus, In client.html
, I wanna send nickname
to server, but the server doesn't receive it successfully.
Any suggestions?
Regards,
Quan.