2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

RustでTCP Serverを立てる

Posted at

概要

RustでシンプルなTCPサーバを立ててみる手順のメモです。

参照

プロジェクトの作成

% cargo new tcp_server_hello_world 
% tcp_server_hello_world
% cargo run                                                                                                      
   Compiling tcp_server_hello_world v0.1.0 (/.../tcp_server_hello_world)
    Finished dev [unoptimized + debuginfo] target(s) in 0.86s
     Running `target/debug/tcp_server_hello_world`
Hello, world!

接続してすぐcloseするTCP Serverの作成

use std::net::{TcpListener, TcpStream};

fn handle_client(_stream: TcpStream) {
}

fn main() -> std::io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:8080")?;

    for stream in listener.incoming() {
        handle_client(stream?);
    }

    Ok(())
}

サーバを起動します。

% cargo run  

telnetで接続してみると、繋がった後、すぐcloseされました。

% telnet 127.0.0.1 8080
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Connection closed by foreign host.

TCP Serverからメッセージを返す

handle_client を少し変更してメッセージを返すようにします。

use std::net::{TcpListener, TcpStream};
use std::io::Write;

fn handle_client(mut stream: TcpStream) {
    stream.write("Hello World!\n".as_bytes()).unwrap();
}

fn main() -> std::io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:8080")?;

    for stream in listener.incoming() {
        handle_client(stream?);
    }

    Ok(())
}

サーバを起動し接続してみると、次のようにメッセージが返ってきます。

% telnet 127.0.0.1 8080
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Hello World!
Connection closed by foreign host.

TCP Serverにメッセージを送信し、同じメッセージを返す

use std::net::{TcpListener, TcpStream};
use std::io::{Read, Write};

fn handle_client(mut stream: TcpStream) {
    let mut buf = [0u8; 1024];
    stream.read(&mut buf).unwrap();
    stream.write(&buf).unwrap();
}

fn main() -> std::io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:8080")?;

    for stream in listener.incoming() {
        handle_client(stream?);
    }

    Ok(())
}

このような結果になり、期待どおりに動きました。

% telnet 127.0.0.1 8080
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Hello World!                              // 入力したメッセージ
Hello World!                              // 返されたメッセージ
Connection closed by foreign host.
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?