This code works great and connects to the socket server that I have running:
var socket = io('http://localhost:8888');
socket.on('news', function (data) {
console.log(data);
socket.emit('evento', { my: 'data' });
});
socket.on('disconnect', function () {
console.log('user disconnected');
});
socket.on('connect', function () {
console.log('user connect');
var data = 'ddsds';
socket.emit('evento', { my: 'data' });
});
On the other hand when I try to use WebSocket()
it fails to connect. This is the code that doesn't work:
var socket = new WebSocket('ws://localhost:8888');
// Open the socket
socket.onopen = function(event) {
// Send an initial message
socket.send('I am the client and Im listening!');
}
// Listen for messages
socket.onmessage = function(event) {
console.log('Client received a message',event);
};
// Listen for socket closes
socket.onclose = function(event) {
console.log('Client notified socket has closed',event);
};
socket.onerror = function(event) {
console.log('error: ',event);
};
It's not an error in the code; I think there is a different way to connect. I need this to work using WebSocket();
. Any help would be greatly appreciated!!