WebSocket Example
Create a real-time chat web-app with WebSocket
To demonstrate how to subscribe to the WebSocket Server API with Javascript, We will create a simple chat script in just 5 minutes. WebSocket is supported in all modern browsers, and we do not need to install any libraries to subscribe to a WebSocket channel.
Note: This example does not use our recommended JavaScript SDK PieSocketJS, and connects directly to the WebSocket Server API.
Create an HTML file
Create an HTML file, let's say piesocket.html, and add some a basic web page structure to it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PieSocket Tester</title>
</head>
<body>
</body>
</html>
Connect to the WebSocket server
Add the following JavaScript into a script tag inside the HTML file to connect to the WebSocket Room.
var apiKey = 'oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm';
var roomId = 1;
var piesocket = new WebSocket(`wss://demo.piesocket.com/v3/${roomId}?api_key=${apiKey}¬ify_self`);
Listen for events
Let's add some code that will be triggered whenever we receive a message on the WebSocket Room.
var apiKey = piesocket.onmessage = function(message) {
alert(`Incoming message: ${message.data}`);
}
Add the chat UI
Let's add some more HTML to build a minimal chat UI
<div id="chatLog">
</div>
<div id="chatFormContainer">
<form id="chatForm">
<input id="chatMessage" placeholder="Type message and press enter..." type="text">
</form>
</div>
Handle events
Let's modify our onmessage so it handles our messages as needed
piesocket.onmessage = function(message) {
var payload = JSON.parse(message.data);
console.log(payload);
if (payload.sender == username) {
payload.sender = "You";
}
if (payload.event == "new_message") {
//Handle new message
chatLog.insertAdjacentHTML('afterend', ` ${payload.sender}: ${payload.text} `);
} else if (payload.event == 'new_joining') {
//Handle new joining
chatLog.insertAdjacentHTML('afterend', ` ${payload.sender} joined the chat`);
}
}
Trigger events
The Websocket client is now ready to handle new_message and new_joining events. Let's trigger those events by publishing a message to our WebSocket room.
We will publish new_message when a user submits the chat form by pressing enter,
and, new_joining when someone joins the room.
We should publish messages from the server-side for better security.
For the sake of simplicity of this demo, we have enabled C2C communication for the demo API from PieSocket cluster settings, to send messages directly from the WebSocket client without a backend.
Let's publish!
Publish new_joining
This is triggered after the websocket connection is established.
var username = `user_${getRandomNumber()}`
piesocket.onopen = function() {
console.log(`Websocket connected`);
//Let others know I have arrived!
piesocket.send(JSON.stringify({
event: 'new_joining',
sender: username,
}));
}
Publish new_message
This function is triggered when the form is submitted.
function sendMessage(e) {
e.preventDefault();
var message = document.getElementById('chatMessage').value;
//Let others know what I have to say
piesocket.send(JSON.stringify({
event: 'new_message',
sender: username,
text: message
}));
}
And this completes our simple WebSocket chat web-app
Wrapping up!
To test this web-app, copy the full code given below and save it into an HTML file. Then, open the HTML file into multiple tabs, send a message from one tab, and check in other tabs. Voila!
Here is the full working code, Happy chatting with yourself!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test PieSocket</title>
<style>
#chatFormContainer {
text-align: center;
position: fixed;
bottom: 5px;
left: 5px;
right: 5px;
}
#chatFormContainer input {
display: inline-block;
width: 90%;
padding: 20px;
}
</style>
</head>
<body>
<div id="chatLog">
</div>
<div id="chatFormContainer">
<form id="chatForm">
<input id="chatMessage" placeholder="Type message and press enter..." type="text">
</form>
</div>
<script>
var username = `user_${getRandomNumber()}`
var apiKey = 'oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm';
var roomId = 1;
var piesocket = new WebSocket(`wss://demo.piesocket.com/v3/${roomId}?api_key=${apiKey}¬ify_self`);
var chatLog = document.getElementById('chatLog');
var chatForm = document.getElementById('chatForm');
chatForm.addEventListener("submit", sendMessage);
piesocket.onopen = function() {
console.log(`Websocket connected`);
piesocket.send(JSON.stringify({
event: 'new_joining',
sender: username,
}));
}
piesocket.onmessage = function(message) {
var payload = JSON.parse(message.data);
console.log(payload);
if (payload.sender == username) {
payload.sender = "You";
}
if (payload.event == "new_message") {
//Handle new message
chatLog.insertAdjacentHTML('afterend', `<div> ${payload.sender}: ${payload.text} <div>`);
} else if (payload.event == 'new_joining') {
//Handle new joining
chatLog.insertAdjacentHTML('afterend', `<div> ${payload.sender} joined the chat<div>`);
}
}
function getRandomNumber() {
return Math.floor(Math.random() * 1000);
}
function sendMessage(e) {
e.preventDefault();
var message = document.getElementById('chatMessage').value;
piesocket.send(JSON.stringify({
event: 'new_message',
sender: username,
text: message
}));
}
</script>
</body>
</html>
