Last active
January 16, 2024 14:02
-
-
Save jakeg/9c85f47eb39297d6f59e6ec8b080b4a5 to your computer and use it in GitHub Desktop.
simple chat server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<title>Live chat</title> | |
<style> | |
#chatHistory { | |
width: 500px; | |
background: black; | |
color: white; | |
padding: 10px; | |
font-size: 16px; | |
height: 500px; | |
} | |
#newMessage { | |
display: block; | |
font-size: 16px; | |
padding: 10px; | |
width: 500px; | |
} | |
</style> | |
<h1>Live chat via <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications">websockets</a></h1> | |
<textarea id="chatHistory"></textarea> | |
<input id="newMessage" placeholder="Send a message..."> | |
<script> | |
let username = window.prompt('What is your name?')||'Lazy' | |
document.cookie = `username=${username}` | |
let ws = new WebSocket(`ws://${location.host}/socket`) | |
chatHistory.value = `Welcome to the chat ${username}! 👋\n` | |
newMessage.focus() | |
ws.onmessage = (e) => { | |
console.log('message received', e) | |
chatHistory.value += e.data + '\n' | |
chatHistory.scrollTop = chatHistory.scrollHeight | |
} | |
newMessage.onkeyup = (e) => { | |
if (e.key === 'Enter' && newMessage.value.length) { | |
ws.send(newMessage.value) | |
chatHistory.value += `${username} (me): ${newMessage.value}\n` | |
newMessage.value = '' | |
chatHistory.scrollTop = chatHistory.scrollHeight | |
} | |
} | |
</script> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let server = Bun.serve({ | |
fetch(req, server) { | |
let cookies = (req.headers.get('cookie')||'').split(';') | |
let username = 'Unknown' | |
for (let pair of cookies) { | |
let [key, value] = pair.split('=') | |
if (key === 'username') username = value | |
} | |
if (server.upgrade(req, { data: { username }})) return | |
return new Response(Bun.file('./index.html')) | |
}, | |
websocket: { | |
open(ws) { | |
let msg = `${ws.data.username} has entered the chat from ${ws.remoteAddress}` | |
console.log(msg) | |
ws.subscribe('chat') | |
ws.publish('chat', msg) | |
}, | |
message(ws, data) { | |
let msg = `${ws.data.username}: ${data}` | |
console.log(msg) | |
ws.publish('chat', msg) | |
}, | |
close(ws) { | |
let msg = `${ws.data.username} has left the chat` | |
console.log(msg) | |
server.publish('chat', msg) | |
ws.unsubscribe('chat') | |
} | |
}, | |
}) | |
console.log(`Chat server listening on ${server.url}`) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment