gio-echo-server: add an example with a SocketService

This lets us use the SocketService we might already want to use and use it for a
websocket server.
This commit is contained in:
Carlos Martín Nieto 2023-03-21 20:04:13 +01:00 committed by Sebastian Dröge
parent fe1c2aeb95
commit 7805e80aec
2 changed files with 68 additions and 0 deletions

View File

@ -140,6 +140,10 @@ required-features = ["async-std-runtime"]
name = "gio-echo"
required-features = ["gio-runtime"]
[[example]]
name = "gio-echo-server"
required-features = ["gio-runtime"]
[[example]]
name = "tokio-echo"
required-features = ["tokio-runtime"]

View File

@ -0,0 +1,64 @@
use std::{env, net::SocketAddr};
use async_tungstenite::{
gio::accept_async,
tungstenite::{Error, Result},
};
use futures::prelude::*;
use gio::{
prelude::*, InetSocketAddress, SocketConnection, SocketProtocol, SocketService, SocketType,
};
use log::info;
async fn accept_connection(stream: SocketConnection) -> Result<()> {
let addr = stream
.socket()
.remote_address()
.expect("SocketConnection should have a remote address");
println!("Peer address: {}", addr);
let mut ws_stream = accept_async(stream)
.await
.expect("Error during the websocket handshake occurred");
while let Some(msg) = ws_stream.next().await {
let msg = msg?;
if msg.is_text() || msg.is_binary() {
ws_stream.send(msg).await?;
}
}
Ok(())
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let _ = env_logger::try_init();
let addr = env::args()
.nth(1)
.unwrap_or_else(|| "127.0.0.1:8080".to_string());
let sockaddr: SocketAddr = addr.parse()?;
let inetaddr: InetSocketAddress = sockaddr.into();
let service = SocketService::new();
service.add_address(
&inetaddr,
SocketType::Stream,
SocketProtocol::Tcp,
glib::Object::NONE,
)?;
println!("Listening on: {}", inetaddr);
service.connect_incoming(|_service, connection, _| {
let stream = connection.clone();
glib::MainContext::default().spawn_local(async move {
accept_connection(stream).await;
});
false
});
let main_loop = glib::MainLoop::new(None, false);
main_loop.run();
Ok(())
}