Skip to content

Commit

Permalink
examples: use SocketListener::accept_future instead of SocketService
Browse files Browse the repository at this point in the history
`SocketService` wraps `SocketListener` to accept connections asynchronously and
pass them along in the callback.

This is unnecessary in an async world as we have `SocketListener::accept_future`
which allows us to accept connections asynchronously in a loop.
  • Loading branch information
carlosmn authored and sdroege committed Jul 8, 2024
1 parent c7b412e commit 6030fe3
Showing 1 changed file with 10 additions and 12 deletions.
22 changes: 10 additions & 12 deletions examples/gio-echo-server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::{env, net::SocketAddr};
use async_tungstenite::{gio::accept_async, tungstenite::Result};
use futures::prelude::*;
use gio::{
prelude::*, InetSocketAddress, SocketConnection, SocketProtocol, SocketService, SocketType,
prelude::*, InetSocketAddress, SocketConnection, SocketListener, SocketProtocol, SocketType,
};

async fn accept_connection(stream: SocketConnection) -> Result<()> {
Expand Down Expand Up @@ -36,25 +36,23 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let sockaddr: SocketAddr = addr.parse()?;
let inetaddr: InetSocketAddress = sockaddr.into();

let service = SocketService::new();
service.add_address(
let listener = SocketListener::new();
listener.add_address(
&inetaddr,
SocketType::Stream,
SocketProtocol::Tcp,
glib::Object::NONE,
)?;
println!("Listening on: {}", inetaddr.to_string());

service.connect_incoming(|_service, connection, _| {
let stream = connection.clone();
glib::MainContext::default().spawn_local(async move {
accept_connection(stream).await.unwrap();
});
false
});

let main_loop = glib::MainLoop::new(None, false);
main_loop.run();
main_loop.context().block_on(async move {
while let Ok((stream, _)) = listener.accept_future().await {
glib::MainContext::default().spawn_local(async move {
accept_connection(stream).await.unwrap();
});
}
});

Ok(())
}

0 comments on commit 6030fe3

Please sign in to comment.