Follow the simple steps below to start sending and receiving messages/events in real-time with the managed WebSocket API.
You can get your API key and API secret from here.
For web-applications, there is no need to install any library or dependency in your project, WebSocket is supported by default in all modern browsers.
var apiKey = 'oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm'; //Demo key, Change this to yours
var channelId = 1;
var piesocket = new WebSocket(`wss://demo.websocket.me/v3/${channelId}?api_key=${apiKey}¬ify_self`);
You can also use the API with: Android, iOS
You are now subscribed to channel 1, read more about the WebSocket API and supported parameters in the WebSocket API section.
When a server or another client sends a message/event, piesocket.onopen
will be fired. Let's write some code to handle this event.
piesocket.onmessage = function(message) {
alert(`Incoming message: ${message.data}`);
}
You are subscribed to channel 1, it's time to send a message.
Here is a PHP example
$curl = curl_init();
$post_fields = [
"key" => "oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm", //Demo key
"secret" => "d8129f82f8dd71910aa4a7efa30a7297", //Demo secret
"channelId" => 1,
"message" => "Hello world!"
];
curl_setopt_array($curl, array(
CURLOPT_URL => "https://www.piesocket.com/api/publish",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($post_fields),
CURLOPT_HTTPHEADER => array(
"Content-Type: application/json"
),
));
$response = curl_exec($curl);
See examples in: NodeJS, Ruby, Python, Java, GO, Shell (curl, wget)
It is possible to publish from a client too, and you can send messages/events to other connected peers using JavaScript from your browser/client without a server.
piesocket.send({
"type": "event",
"name": "test-event",
"message": "Hello world!"
});
or just this:
piesocket.send("Hello world!");
This will only work when C2C (Client-to-client) communications are enabled for your API in API settings. C2C is enabled by default (for backward compatibility) and you MUST disable it for better security.
Please note that when you enable C2C, anyone with your API KEY
can publish messages/events to your channels. The SECRET_KEY
will no longer be required.
This is why we recommend you disable C2C for your API key and only use the server-side code to publish messages wherever possible.
If C2C is enabled (not recommended) for your API key, You can use our WebSocket tester to publish and receive messages.
See full working code examples in the following sections:
Facing difficulties with the integration? Use the chat box on the bottom-right corner of this page to reach us.