Yesterday I started using this module. I am trying to make a chat for something using websockets.
I have a problem: I do not know how to transfer a message that sends a client to the server, and then show it to all users. On the server side, I have this code:
var ipaddress = 'localhost';
var port = 8080;
var WebSocketServer = require('ws').Server
, ws = new WebSocketServer({host:ipaddress, port:port});
ws.on('connection', function(ws) {
console.log('New connection');
ws.on('message', function(message) {
ws.send(message);
});
});
console.log('Listening to ' + ipaddress + ':' + port + ' ...');
And on the client side, this other code:
jQuery(document).ready(function($) {
var content = $('#screen');
var message = $('input[type="text"]').val();
var ws = new WebSocket('ws://localhost:8080');
ws.onopen = function() {
console.log('Connected');
};
$('input[type="button"]').click(function() {
ws.send(message);
});
ws.onmessage = function(msg) {
console.log('Received message from server: ' + msg.data);
addMessage(msg.data);
}
function addMessage(message) {
content.prepend('<p><span>' + message + '</span></p>');
}
});
user2088019
source
share