Replies: 2 comments 3 replies
-
I think you can use websockets for this |
Beta Was this translation helpful? Give feedback.
3 replies
-
Happy New Year. Recently I have spent some time work on this issue, and got a simplified working example
import asynchttpserver, asyncdispatch, times, asyncnet, strformat, os, mimetypes
proc serveStaticFile(req: Request, filePath: string) {.async.} =
if not fileExists(filePath):
let msg = "HTTP/1.1 404 Not Found\c\LContent-Length: 0\c\L\c\L"
await req.client.send(msg)
return
let content = readFile(filePath)
let mimes = newMimetypes()
let contentType = mimes.getMimetype(filePath.splitFile.ext)
var msg = "HTTP/1.1 200 OK\c\L"
msg.add("Content-Type: " & contentType & "\c\L")
msg.add("Content-Length: " & $content.len & "\c\L")
msg.add("\c\L")
msg.add(content)
await req.client.send(msg)
proc handleSSE(req: Request) {.async.} =
# Create HttpHeaders object and set the headers for SSE
let headers = {
"Connection": "keep-alive",
"Content-Type": "text/event-stream; charset=utf-8",
"Cache-Control": "no-cache",
"Content-Length": ""
}.newHttpHeaders()
# Send the headers
await req.respond(Http200, "", headers)
# Send a continuous stream of messages
while true:
let now = now().utc.format("ddd, d MMM yyyy HH:mm:ss")
# Send time event
let timeMessage = "event: time\ndata: {now}\n\n".fmt
await req.client.send(timeMessage)
await sleepAsync(1000) # Wait for 1 second before sending the next message
proc handleRequest(req: Request) {.async.} =
echo fmt"Received request: {req.url.path}"
case req.url.path
of "/":
await serveStaticFile(req, "public/index.html")
of "/events":
await handleSSE(req)
else:
let publicPath = "public" & req.url.path
if fileExists(publicPath):
await serveStaticFile(req, publicPath)
else:
let msg = "HTTP/1.1 404 Not Found\c\LContent-Length: 0\c\L\c\L"
await req.client.send(msg)
proc main() {.async.} =
var server = newAsyncHttpServer()
server.listen(Port(8080), "0.0.0.0")
echo "Starting server on 0.0.0.0:8080..."
while true:
if server.shouldAcceptRequest():
await server.acceptRequest(handleRequest)
else:
# too many concurrent connections
await sleepAsync(500)
waitFor main()
<!DOCTYPE html>
<html>
<head>
<title>SSE Demo with HTMX</title>
<script src="https://unpkg.com/htmx.org@2.0.4"></script>
<script src="https://unpkg.com/htmx-ext-sse@2.2.2/sse.js"></script>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 20px auto;
padding: 0 20px;
}
#messages {
height: 400px;
width: 100%;
overflow-y: auto;
border: 1px solid #ccc;
padding: 10px;
margin-bottom: 10px;
background: #f9f9f9;
}
.message {
margin: 5px 0;
padding: 8px;
border-bottom: 1px solid #eee;
background: white;
border-radius: 4px;
animation: fadeIn 0.5s;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(-10px); }
to { opacity: 1; transform: translateY(0); }
}
.timestamp {
color: #666;
font-size: 0.8em;
}
#status {
padding: 10px;
margin: 10px 0;
border-radius: 4px;
}
.connected {
background-color: #dff0d8;
color: #3c763d;
}
.disconnected {
background-color: #f2dede;
color: #a94442;
}
.time-event { color: #31708f; }
.open-event { color: #3c763d; }
.heartbeat-event { color: #777; }
.price-event { color: #8f0a1a; }
</style>
</head>
<body>
<h1>Server-Sent Events Demo (HTMX)</h1>
<!-- Current Time -->
<div id="current-time"
class="message time-event"
hx-ext="sse"
sse-connect="/events"
sse-swap="time">
Waiting for time update...
</div>
</body>
</html> but I am not sure how to integrate it in happyx, it would be nice to you can offer some help! |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Server-Sent Events (SSE) is a technology where a server can push updates to a client over an HTTP connection. The client, typically a web browser, makes a single request to the server, and the server can keep the connection open and continuously send data (events) to the client. This enables the server to update the client in real-time without the client needing to constantly request new data (also known as polling).
Key Features of SSE:
One-way communication: SSE allows servers to push data to clients but does not support two-way communication.
Text-based: Data sent from the server is typically sent as text (UTF-8 encoded).
Automatic reconnection: If the connection is lost, SSE provides a built-in mechanism to reconnect automatically.
Is there a Server-Sent Event (SSE) Support in HappyX, if not, can I try implementing it with what's available?
Beta Was this translation helpful? Give feedback.
All reactions