코딩Coding/Rust연습

Rust WebSocket구현 ChatGPT

내인생PLUS 2023. 5. 28. 20:54
728x90



WebSocket

use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use tokio_tungstenite::connect_async;
use tokio_tungstenite::tungstenite::protocol::Message;

#[tokio::main]
async fn main() {
    // Connect to the WebSocket server
    let stream = TcpStream::connect("127.0.0.1:8080").await.unwrap();
    let (mut ws_stream, _) = connect_async(stream).await.expect("Failed to connect to WebSocket");

    println!("Connected to WebSocket server");

    // Send a message to the server
    let message = Message::text("Hello, WebSocket server!");
    ws_stream.write_message(message).await.expect("Failed to send message");

    // Receive messages from the server
    loop {
        let received = ws_stream.read_message().await.expect("Failed to receive message");
        match received {
            Ok(message) => {
                println!("Received message: {:?}", message);
            }
            Err(err) => {
                println!("Failed to receive message: {:?}", err);
                break;
            }
        }
    }
}



Cargo.toml

[dependencies]
tokio = { version = "1", features = ["full"] }
tokio-tungstenite = "0.15.0"



ChatGPT라 맞는지 테스트 해봐야함 ㅋ














반응형