Skip to content

Commit

Permalink
fix(serve): websocket implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
clearloop committed Dec 31, 2023
1 parent 5ddd822 commit be3f3f5
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 5 deletions.
48 changes: 48 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ notify = { version = "6.1.1", optional = true }
tokio = { version = "1.35.1", features = [ "rt-multi-thread" ], optional = true }
warp = { version = "0.3.6", optional = true }
futures = { version = "0.3.30", optional = true }
async-lock = "3.2.0"

[features]
default = [ "cli" ]
Expand Down
1 change: 0 additions & 1 deletion blog/templates/layout.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
<script>
const socket = new WebSocket(`ws://${location.host}` + "/" + "{{{ livereload }}}");
socket.onmessage = function (event) {
console.log(event)
if (event.data === "reload") {
socket.close();
location.reload();
Expand Down
10 changes: 6 additions & 4 deletions src/cmd/serve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@
use crate::{cmd::Watch, LIVERELOAD_ENDPOINT};
use anyhow::Result;
use async_lock::Mutex;
use ccli::{clap, clap::Parser};
use futures::{sink::SinkExt, FutureExt, StreamExt};
use notify::Event;
use std::{
net::{Ipv4Addr, TcpListener},
sync::{
mpsc::{self, Receiver},
Arc, Mutex,
Arc,
},
};
use tokio::runtime::Runtime;
Expand Down Expand Up @@ -59,9 +60,10 @@ impl Serve {
.map(|ws: Ws, rx: Arc<Mutex<Receiver<Event>>>| {
ws.on_upgrade(move |socket: WebSocket| async move {
let (mut tx, _) = socket.split();
if let Ok(rx) = rx.lock() {
if rx.recv().is_ok() {
let _ = tx.send(Message::text("reload"));
let rx = rx.lock().await;
if rx.recv().is_ok() {
if let Err(e) = tx.send(Message::text("reload")).await {
tracing::error!("failed to send reload message: {}", e);
}
}
})
Expand Down

0 comments on commit be3f3f5

Please sign in to comment.