Hi, I'm trying to use the client library in the browser, but I'm getting tripped up by the "require" syntax. How do I fix this error message?
Uncaught ReferenceError: require is not defined
In client side you can use this:
var socket = new WebSocket('ws://ip:port')
Its vanilla JS then handle events with: socket.onopen socket.onclose socket.onerror socket.onmessage = callback
The client library is not for use in the browser. Modern up to date browsers come with their own Websocket Object you can use to create connections. The client library is for use in node.js to create client connections to your server for testing or other purposes.
Thanks @rodel77, but it's not working for me. The callback functions are never fired. :/
var ws = new WebSocket('ws://120.0.0.1:8889');
console.log('connecting to server...');
ws.onopen = function open() {
console.log('connected to server!')
};
ws.onmessage = function incoming(data, flags) {
console.log('got a message! ' + JSON.stringify(data));
}
Server:
const WebSocket = require('ws');
const util = require('util');
const wss = new WebSocket.Server({ port: 8889 });
I dont know if this matter but try to add connection listener to server
wss.on('connnection', function(client){})
Are you doing this on your computer or you are connecting to a remote server?
If remote then make sure 120.0.0.1:8889 is the right ip:port if on your computer use localhost 127.0.0.1:8889
wss.on('connnection', function(client){
//do something with client here
});
@LordMajestros - Hmm it's saying, "wss.on is not a function"
Are you sure you are calling the WebSocket.Server var like this?
const wss = new WebSocket.Server({ port: 8889 });
wss.on('connection', (client) => {
console.log(client);
});
On the server I am, but the problem I'm having is in the client code.
And "WebSocket" var in client its called wws?
In the example i put first is var socket = new WebSocket('ws://ip:port') then you have to use socket.onopen = function(){console.log('Callback')};
Ah, I think I was entering the ip address wrong. facepalm
Thanks @rodel77. The syntax you gave here is working for me. 馃憤