LoginSignup
9
8

More than 5 years have passed since last update.

【Ruby+Unity】開発に便利!簡易Webサーバを立ち上げ通信内容を確認

Posted at

内容と仕様

スマホアプリの開発してるとHTTP通信のheaderやpost値を確認したくなることがたまにあるのでRubyで簡易Webサーバを立ち上げ、通信の中身を確認する

簡易Webサーバ

server.rb
# -*- coding: utf-8 -*-
IP       = '0.0.0.0'
PORT     = '8080'
DOC      =  './'

require 'webrick'
opts  = {
    :BindAddress    => IP,
    :Port           => PORT,
    :DocumentRoot   => DOC,
}

server = WEBrick::HTTPServer.new(opts)
server.mount_proc("/") { |req, res|
  res.body = req.to_s
}

#コマンドラインでCtrl+Cした場合止めるイベントハンドラ
Signal.trap(:INT){ server.shutdown}

#サーバースタート
server.start
サーバ起動
>ruby server.rb 
[2015-10-09 11:36:25] INFO  WEBrick 1.3.1
[2015-10-09 11:36:25] INFO  ruby 2.2.3 (2015-08-18) [x86_64-darwin13]
[2015-10-09 11:36:25] INFO  WEBrick::HTTPServer#start: pid=91225 port=8080

動作確認

■ ブラウザでHTTP GETの試験
スクリーンショット 2015-10-09 11.41.10.png

■ curlでHTTP POSTの試験

>curl -F "name1=value1" -F "name2=value" http://localhost:8080/hoge/hoge
POST /hoge/hoge HTTP/1.1
User-Agent: curl/7.30.0
Host: localhost:8080
Accept: */*
Content-Length: 245
Expect: 100-continue
Content-Type: multipart/form-data; boundary=----------------------------af153bdb71ef

------------------------------af153bdb71ef
Content-Disposition: form-data; name="name1"

value1
------------------------------af153bdb71ef
Content-Disposition: form-data; name="name2"

value
------------------------------af153bdb71ef--

■ Unityから接続試験
スクリーンショット 2015-10-09 11.57.21.png

UnityCode
        // Web
        Debug.LogWarning("-----------");
        using(WWW www = new WWW("http://127.0.0.1:8080/unity/from_unity?v1=1&v2=2")){
            yield return www;
            Debug.LogWarning(www.text);
        }
        Debug.LogWarning("-----------");

特徴

どんなURLでも応答を返す

9
8
2

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
9
8