Skip to content

Instantly share code, notes, and snippets.

View tsidea's full-sized avatar

Tudor Sidea tsidea

  • Bokuseki
  • Bucharest, Romania
View GitHub Profile
@tsidea
tsidea / simple_hello_server.rs
Last active February 3, 2021 04:06
simple hello server
use std::convert::Infallible;
use std::net::SocketAddr;
use hyper::{Body, Request, Response, Server, server::conn::AddrStream};
use hyper::service::{make_service_fn, service_fn};
async fn handle_request(request: Request<Body>, remote_addr: SocketAddr) -> Result<Response<Body>, Infallible> {
Ok(Response::new(Body::from(format!("Hello there connection {}\n", remote_addr))))
}
#[tokio::main(flavor = "current_thread")]
@tsidea
tsidea / simple_http_handle_request.rs
Created February 1, 2021 19:00
simple http handler
use hyper::header;
...
async fn handle_request(mut request: Request<Body>, remote_addr: SocketAddr) -> Result<Response<Body>, Infallible> {
match (request.uri().path(), request.headers().contains_key(header::UPGRADE)) {
//if the request is ws_echo and the request headers contains an Upgrade key
("/ws_echo", true) => {
//handle websocket HERE
...
@tsidea
tsidea / spawn_ws_conn.rs
Last active September 14, 2022 04:22
spawn task to handle websocket connection
use hyper::upgrade;
use tokio_tungstenite::WebSocketStream;
use futures::stream::StreamExt;
...
tokio::spawn(async move {
//using the hyper feature of upgrading a connection
match upgrade::on(&mut request).await {
//if successfully upgraded
@tsidea
tsidea / ws_handshake_response.rs
Created February 1, 2021 19:03
create websocket hanshake response
use tungstenite::{handshake, Error};
...
match handshake::server::create_response_with_body(&request, || Body::empty()) {
Ok(response) => {
//handle websocket connection HERE
...
//return the response to the handshake request
response
@tsidea
tsidea / complete_handle_request.rs
Created February 1, 2021 19:04
complete request handler for ws and http
use std::convert::Infallible;
use std::net::SocketAddr;
use hyper::{header, upgrade, StatusCode, Body, Request, Response, Server, server::conn::AddrStream};
use hyper::service::{make_service_fn, service_fn};
use tokio_tungstenite::WebSocketStream;
use tungstenite::{handshake, Error};
use futures::stream::StreamExt;
async fn handle_request(mut request: Request<Body>, remote_addr: SocketAddr) -> Result<Response<Body>, Infallible> {
match (request.uri().path(), request.headers().contains_key(header::UPGRADE)) {