This library is a wrapper around the WebSocket API for use with Node.JS and web applications. There is also a lite version that uses raw TCP sockets for client-to-server communication rather than the websocket protocol.
server.js (Node.JS server-side)
const Server = require('./server');
const server = new Server();
server.on('client', client => {
client.on('packet', data => {
// Handle data from client
});
client.on('disconnect', event => {
// Handle client disconnect
});
});
server.listen({ port: 8080, path: '/ws' });
index.html (HTML client-side)
<!DOCTYPE html>
<head>
<!-- Serializer has to be imported in html manually
and must be a global variable. For example, moai uses
a custom serializer although you could customize that
by exporting Serializer#encode() and Serializer#decode()
functions of your own.
-->
<script src="./serializer.js">
<!-- Moai client-side import -->
<script src="./client.js">
<script>
// Client-side code.
let client = new Client();
client.connect(new URL("ws://127.0.0.1:8080/ws"), connected => {
if(connected) {
// Connected
client.on('packet', data => {
// Handle data from server
});
client.on('disconnect', event => {
// Handle disconnect
});
} else {
// Connection failed
}
});
</script>
</head>
- Easy to use
- Allows transmission of JSON
Moai-Web | Moai-Lite | |
---|---|---|
Protocol | TCP | |
Serializer | SimpleSerializer | |
Web Support | ✅ | Requires custom solution |
Raw TCP Socket support | ❌ | ✅ |