Hi all! I'd like to show you a simple text chat over HTTP/HTTPS using Piping Server, which was introduced in Data Streaming between Every Device over HTTP/HTTPS.
Demo video
Here is a simple demo video of the chat.
How to use Piping Server in JavaScript?
The purpose of Piping Server is data transfer.
Here is an usage. Send by POST method, Get by GET method.
// Send
fetch("https://ppng.io/mytext", {
method: "POST",
body: 'hello, world'
})
// Get
const res = await fetch("https://ppng.io/mytext")
await res.text() // === 'hello, world'
You can change /mytext
and "https://ppng.io" freely. An easy way to run Piping Server is using Heroku. You can click [Deploy to Heroku] on Piping Server on GitHub.
By using this, you can build a simple chat without WebSocket or WebRTC.
Try on CodePen
Codepen: https://codepen.io/nwtgck/pen/xNoKgx
Both CodePens are the same.
Full code
Here is the whole code of chat.
<html>
<head>
<title>Simple Chat via Piping Server</title>
<style>
.me {
text-align: right;
}
</style>
</head>
<body>
<p>
<input placeholder="Your ID" id='your_id'>
<input placeholder="Peer ID" id='peer_id'>
<button onclick='receiveLoop(this)'>Connect</button>
</p>
<p style='position: absolute; bottom: 0;'>
<input placeholder="Message" id='message' size='50'>
<button onclick="send()">Send</button>
</p>
<hr>
<div id='talks'>
<!--This will be added by JavaScript -->
</div>
<script>
// Receive-loop
async function receiveLoop(btn) {
your_id.disabled = peer_id.disabled = btn.disabled = true;
while(true) {
try {
// Get peer's response
const res = await fetch(`https://ppng.io/${peer_id.value}-${your_id.value}`);
// Create talk element
const talk = document.createElement('div');
// Set peer's message
talk.innerText = await res.text();
// Add peer's message
talks.appendChild(talk);
} catch(err) {
console.error(err);
}
}
}
// Send your message
function send() {
// Send your message
fetch(`https://ppng.io/${your_id.value}-${peer_id.value}`, {
'method': 'POST',
body: message.value
});
// Create talk element
const talk = document.createElement('div');
talk.innerText = message.value;
talk.classList.add('me');
talks.appendChild(talk);
// Empty your message
message.value = '';
}
</script>
</body>
<html>
Secure chat via Piping Server
You can find more secure chat in the following. The application is written in Vue in TypeScript.
GitHub: https://github.com/nwtgck/piping-chat-web
The features are the following.
- End-to-End Encryption by AES GCM
- Forward Secrecy by ECDH
- Public Key Authentication like SSH
- via Piping Server
- Static hosting
- Progressive Web App (PWA)
- Accountless
Thanks
@karanganesan told me that a simpler example will be useful. This is why I wrote this post. Thanks Karan!
can you share any simpler examples of using Piping Server like : only pure vanilla javascript and bare minimum like working chat using piping without any Vue JS or anything.