WorkerRoleへ外部から接続 で、外部に接続できる事が分かった。
Azure上でIronRuby動作を目指し、WorkerRoleでIronRubyを目指そうと思う
IronRubyとWeb
通常のRubyでWebアプリケーションというと Ruby on Rails というアプリケーション フレームワークを使う。
また、WebアプリケーションフレームワークとWebサーバを接続する為には、Rackという 層が用意されている。
Azure上で IronRubyを使うためには以下のような道具があるかと思う
-
IIS
いわずとしれた Windows用 Web Server -
WebRick
pure ruby で記述されている Web Server -
Thin
ruby用のWeb Server -
.NET HttpListener
.NET 2.0以降で利用できる .NET環境用Webサーバライブラリ
これらのどれかと Rack がつなぎ込めればいいと思う。
今回は「.NET HttpListener」との接続で検討する。
.NET HttpListener
このライブラリは以下のように利用する。
int port = 8080;
var prefix = string.Format("http://*:{0}/",port); // 受け付けるURL
HttpListener listener = new HttpListener();
listener.Prefixes.Add(prefix); // プレフィックスの登録
listener.Start(); //スタート
while(true)
{
HttpListenerContext context = listener.GetContext();
HttpListenerRequest req = context.Request;
HttpListenerResponse res = context.Response;
var s = @"<html><head><title>タイトル</title></head><body>hello</body></html>";
var content = System.Text.Encoding.UTF8.GetBytes(s);
res.OutputStream.Write(content, 0, content.Length);
res.Close();
}
- HttpListenerオブジェクトを作成
- Prefixesの追加及びStart()でサーバを開始
- listener.GetContext()でリクエストを取得(リクエストが到着するまでブロック)
- 得られたコンテキストからHttpListenerRequest及びHttpListenerResponseを取得
- 応答文字列を作成し、返答し Close()
WorkerRole との結合
以下のコードで結合してみた。
public override void Run()
{
// This is a sample worker implementation. Replace with your logic.
Trace.WriteLine("WorkerRole1 entry point called", "Information");
try
{
HttpServerInit();
}
catch (Exception ex)
{
Trace.WriteLine("Exception HttpServerInit ", "Information");
Trace.WriteLine(ex.ToString() , "Information");
Trace.WriteLine(ex.StackTrace, "Information");
}
while (true)
{
try
{
HttpServerProcess();
}
catch (Exception ex )
{
Trace.WriteLine("Exception HttpServerProcess ", "Information");
Trace.WriteLine(ex.ToString(), "Information");
Trace.WriteLine(ex.StackTrace, "Information");
}
Thread.Sleep(10000);
Trace.WriteLine("Working", "Information");
}
}
HttpListener listener;
private void HttpServerInit()
{
var port = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["IronRubyHttp"].IPEndpoint.Port;
var prefix = string.Format("http://*:{0}/",port); // 受け付けるURL
listener = new HttpListener();
listener.Prefixes.Add(prefix); // プレフィックスの登録
listener.Start();
}
private void HttpServerProcess()
{
HttpListenerContext context = listener.GetContext();
HttpListenerRequest req = context.Request;
HttpListenerResponse res = context.Response;
var s = @"<html><head><title>タイトル</title></head><body>hello</body></html>";
var content = System.Text.Encoding.UTF8.GetBytes(s);
res.OutputStream.Write(content, 0, content.Length);
res.Close();
}
結果
しかし、以下のコードで例外が発生し成功しない。
try
{
HttpServerInit();
}
catch (Exception ex)
{
Trace.WriteLine("Exception HttpServerInit ", "Information");
Trace.WriteLine(ex.ToString() , "Information");
Trace.WriteLine(ex.StackTrace, "Information");
}
まとめ
WorkerRoleでHttpListenerを単純に使うわけにはいかないようである。


コメントする