I started learning node.js. I want to make a chat application using websockets. In console it's working fine. But in browser i'm getting
Uncaught ReferenceError: require is not defined
I googled and saw this answer. I want to try browserify but it's not working properly. Here is my js file
client.js:
var WebSocket = require('websocket');
var connector;
var WebSocketClient = WebSocket.client;
var client = new WebSocketClient();
client.on('connectFailed', function (error) {
console.log('Connect Error: ' + error.toString());
setTimeout(self.connect, 2000);
});
client.on('connect', function (connection) {
connector = connection;
console.log('WebSocket Client Connected');
connection.on('error', function (error) {
errorStr = error.toString();
console.log("Connection Error: " + errorStr);
});
connection.on('close', function () {
console.log('echo-protocol Connection Closed');
});
connection.on('message', function (message) {
if (message.type === 'utf8') {
console.log("Received: '" + message.utf8Data + "'");
}
});
connection.sendUTF("Hello");
sender("Working");
});
client.on('error', function (err) {
console.log("It's an Err " + err.toString());
});
function connect() {
client.connect('ws://localhost:8765/', 'echo-protocol');
}
function sender(str) {
connector.sendUTF(str);
}
connect();
Here is the problem. When I run bunddle.js.
$ browserify client.js > bunddle.js
$ node bunddle.js
/home/user/udb/sgg/node/chat/bundle.js:5
var client = new WebSocketClient();
^
TypeError: undefined is not a function
The websocket
library you are using involves some native C++ bindings. These are incompatible with browserify so you cannot use it. You should use the library only in your server-implementation and in your client.js that runs in the browser you should use the WebSocket
object.
Browsers provide their own WebSocket
object. The websocket
NPM package you are using is a Node.js implementation of the browser-standard WebSocket
interface (Well, the websocket.W3CWebSocket
class anyway).
Essentially in browsers you should not need require('websocket')
or anything similar as the browsers already provide you with the WebSocket. See the MDN example for an example of using WebSockets in the browser.
Of course given WebSockets provide a communication method between two endpoints, you will need an endpoint with which your browser will communicate. This is where you need a package like the websocket
: Implementing the server-side endpoint with which the browser communicates.
From the doc itself: https://github.com/websockets/ws
Note: This module does not work in the browser. The client in the docs is a reference to a back end with the role of a client in the WebSocket communication.
Browser clients must use the native WebSocket object. To make the same code work seamlessly on Node.js and the browser
you can use one of the many wrappers available on npm, like isomorphic-ws.
The native api and implementation is just cool and sufficient
(don't see a motivation for isomorphic-ws)
https://developer.mozilla.org/en-US/docs/Web/API/WebSocket
webSocket = new WebSocket(url, protocols);
const ws = new WebSocket("wss://www.example.com/socketserver");
You need to JSON.stringify
. And ws in the backend will handle it all right.
https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
ws.send(JSON.stringify(data));
Note that you don't have the on('event') api But instead onopen, onmessage, onclose, ... methods to set
ws.onmessage = function (event) {
console.log(event.data);
}
Or by using events and addEventListner
// Create WebSocket connection.
const socket = new WebSocket('ws://localhost:8080');
// Connection opened
socket.addEventListener('open', function (event) {
socket.send('Hello Server!');
});
// Listen for messages
socket.addEventListener('message', function (event) {
console.log('Message from server ', event.data);
});
The total events are: open, close, message, error.
And it's nice to look out the doc, and also the tutorial here
https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With