These examples have been created for various courses introducing methods for creating networked experiences with only frontend coding in P5. To work with this code you will need a free PubNub account. Messages are sent/received as JSON , so you can create multiple levels of complexity. I have generally found the latency to be about 100ms.
Get your publish and subscribe keys from your account. Define a global variable to hold the PubNub object. Also define the name of a channel to broadcast on within your account. Messages can be sent/received on multiple channels.
letdataServer;letpubKey='insert your pub key';letsubKey='insert your sub key';letchannelName="messageChannel";
Within the setup function initialize the connection, subscribe to the channel, and create a listener to run a callback function any time a new message arrives.
functionsetup(){createCanvas(windowWidth,windowHeight)// initialize pubnubdataServer=newPubNub({publish_key : pubKey,//get these from the pubnub account onlinesubscribe_key : subKey,ssl: true//enables a secure connection. });//attach callbacks to the pubnub object to handle messages and connectionsdataServer.addListener({message: readIncoming});dataServer.subscribe({channels: [channelName]});}
Define a callback function to execute each time a message is received
functionreadIncoming(inMessage)//when new data comes in it triggers this function, {// this works becsuse we subscribed to the channel in setup()// simple error check to match the incoming to the channelNameif(inMessage.channel==channelName){incomingText=inMessage.message.messageText;}}
Create a function that publishes messages to the channel. These are JSON format
functionsendTheMessage(){// Send Data to the server to draw it in all other canvasesdataServer.publish({channel: channelName,message:
{who: whoAreYou.value(),messageText: sendText.value()//get the value from the text box and send it as part of the message }});}