Skip to content

Client Side Example Code

Daniel M. Hendricks edited this page Dec 1, 2019 · 1 revision

Below is a basic example of listening for Socket.IO message on web sites. The nodejs-simple-message-relay server must be running in order for this to work.

First, link to the Socket.IO client in your page head:

<script src="https://cdn.jsdelivr.net/npm/socket.io-client@2.3/dist/socket.io.slim.js"></script>

Add an element to you page body that will be used to display incoming messages:

<h3>Messages Received</h3>
<div id="messages"></div>

Finally, add some JavaScript to initialize Socket.IO, configured to listen to the socket name of your choice (in this example, my-socket-name), and append incoming messages to HTML element above:

var socket = io.connect( 'http://127.0.0.1:3000' );
var messageElement = document.getElementById( 'messages' );

// Append incoming messages to the #message HTML element
socket.on( 'my-socket-name', function( payload ) {
    console.log( 'Received:', payload ); 
    messageElement.innerText += payload.message + '<br />' );
});

Sending Messages

Using the example above, you can send messages using Postman or cURL to send a POST to the /send endpoint:

curl -X POST 'http://localhost:3000/send/my-socket-name?api_key=YOUR_API_KEY' \
  -H 'Content-Type: application/json' \
  -d '{ "message": "Hello world!" }'
Clone this wiki locally