PieSocket Javascript Client
PieSocket Channels - JavaScript SDK
PieSocket offers PieSocketJS for easy integration into Web applications.
This SDK is a JavaScript library and it can be used with any JavaScript framework such as ReactJS, VueJS, Angular, etc.
Channels SDK implements auto-reconnections among other best WebSocket practices.
Getting started
Add PieSocektJS into your application.
Yarn
yarn add piesocket-js@5
NPM
npm i piesocket-js@5
CDN
Add following script tag in the head section of your HTML file
<script src="https://unpkg.com/piesocket-js@5"></script>
Usage
You are now ready to use PieSocket Channels in your application.
Import PieSocket
Import module:
import PieSocket from 'piesocket-js';
With CDN/Browser:
Use the PieSocket.default global variable, e.g. var piesocket = new PieSocket.default({...})
Initialize PieSocket
Define your API Key, Cluster ID and pass it to PieSocket class.
Get your API key and Cluster ID here: Create PieSocket account
var pieSocket = new PieSocket({
clusterId: "demo",
apiKey: "VCXCEuvhGcBDP7XhiJJUDvR1e1D3eiVjgZ9VRiaV",
notifySelf: true
});
If you are using the script tag to load PieSocket, please use following
var pieSocket = new PieSocket.default({...});
To see the full list of available configuration options,
See: PieSocket Configuration Options
Subscribe to a Channel
Subscribe to a Channel
pieSocket.subscribe("chat-room").then((channel)=>{
console.log("Channel is ready")
})
Here chat-room is what we call a roomId. You need this ID to publish messages from your server.
Listen to an event
Use the following code to attach an event listener for any event.
pieSocket.subscribe("chat-room").then((channel)=>{
console.log("Channel is ready");
channel.listen("new_message", (data, meta)=>{
console.log("New message: ", data);
});
});
There are system events like system:member_joined, system:member_left, etc. You can listen to these events to build a beautiful realtime-connected experience.
See a list of all system events here: All system events
Publish Events
Use the publish method to publish an event from the client itself.
You must enable client-to-client communication setting for the PieSocket cluster to make this work, in new clusters it is enabled by default.
channel.publish("new_message", {
from: "Anand",
message: "Hello PieSocket!"
})
Developers usually publish events from the backend-server.
See: How to publish events from server
Room members
You can see who is in a room, get system:member_joined to fire and track when people leave by enabling Presence features in a room.
var pieSocket = new PieSocket({
...
presence: true
});
List all members
To get a list containing all members of the room, use the following code
var members = channel.members;
Same is possible from your server, see the REST API section
Get current member
To get information about the current member, use following code
var member = channel.getCurrentMember();
User Authentication
PieSocket lets you block un-authorized connections and identify users with the help of JWT authentication tokens.
To learn more, like how to set an User ID, what are Private Channels, etc.
See the: Authentication guide
Set Authentication Endpoint
Set an Authentication URL which generates and responds with JWT tokens. Channels SDK makes a POST request to this URL with Channel information, everytime an user tries to connect to a private room.
var pieSocket = new PieSocket({
...
authEndpoint: "https://mywebsite.com/generate-jwt"
});
Optional: Add headers to the authEndpoint request
var pieSocket = new PieSocket({
...
authHeaders: {
"Accept": "application/json",
"Content-type" => "application/json"
}
});
The URL should respond with thefollowing JSON on successful authentication.
{"auth":"*************"}
Set JWT Token
To skip the authEndpoint call, and set the JWT yourself, use the following method.
var pieSocket = new PieSocket({
...
jwt: "https://mywebsite.com/generate-jwt"
});
Leave a Channel
To unsubscribe from a Channel and close the ongoing WebSocket connection, use the following code.
All event listeners on this Channel will be removed.
pieSocket.unsubscribe("chat-room")
Example: Chat room
Let's use PieSocket channels to build a serverless chatroom within a single HTML file.
Copy the code below and paste it into an HTML file, say piesocket.html
<!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>
<style>
div{
margin:10px;
}
#chatFormContainer {
text-align: center;
position: fixed;
bottom: 5px;
left: 5px;
right: 5px;
}
#chatFormContainer input {
display: inline-block;
width: 90%;
padding: 20px;
}
</style>
<script src="https://unpkg.com/piesocket-js@5"></script>
</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_"+(Math.floor(Math.random() * 1000));
var chatLog = document.getElementById('chatLog');
var chatForm = document.getElementById('chatForm');
chatForm.addEventListener("submit", sendMessage);
var piesocket = new PieSocket.default({
clusterId: "demo",
apiKey: "YOUR_API_KEY",
notifySelf: true,
presence: true,
userId: username
});
var channel;
piesocket.subscribe("chat-room").then( ch => {
channel = ch;
channel.listen("system:member_joined", function(data){
if(data.member.user == username){
data.member.user = "<b>You</b>";
}
chatLog.insertAdjacentHTML('afterend', `<div> ${data.member.user} joined the chat<div>`);
})
channel.listen("new_message", function(data, meta){
if(data.sender == username){
data.sender = "<b>You</b>";
}
chatLog.insertAdjacentHTML('afterend', `<div> ${data.sender}: ${data.text} <div>`);
})
});
function sendMessage(e) {
e.preventDefault();
if(!channel){
alert("Channel is not connected yet, wait a sec");
return;
}
var message = document.getElementById('chatMessage').value;
channel.publish("new_message", {
sender: username,
text: message
});
}
</script>
</body>
</html>
Replace YOUR_API_KEY with an API key, you can get from Channels dashboard.
Right-click on piesocket.html and open with Google Chrome, in multiple tabs. You should be able to chat with yourself! Make it even more interesting, host this file on a web-server and send the link to your friend from the other corner of the world to chat with them in real-time.
