简体   繁体   中英

Text messaging using a-frame

I want to add a text chat system in a-frame. I'm using.networked a-frame as connectivity can be anything possible with that or I've to do using some other tech.

There is a simple API to send custom messages with the.network layer that is already setup:

// subscribe to custom data
NAF.connection.subscribeToDataChannel(dataType, (senderId, dataType, data, targetId) => {})

// send custom data
NAF.connection.broadcastData(dataType, data)

So sending an chat message is as simple as:

const btn = document.querySelector("button");      // SEND btn
const input = document.querySelector("input");     // input field with the text
const log = document.querySelector("#messages")    // message log

// when you want to send a message
btn.addEventListener("click", evt => {
  // log your own messages
  messages.innerHTML += NAF.clientId + ": " + input.value + '<br>'
  // broadcast the text as some unique dataType (like "chat")
  NAF.connection.broadcastData("chat", {txt: input.value}) 
})

// when a "chat" type message arrives
NAF.connection.subscribeToDataChannel("chat", (senderId, dataType, data, targetId) => {
  // append the data.txt to the message log
  messages.innerHTML += senderId + ": " + data.txt + '<br>'
})

Check it out in this glitch :

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM