Sunday, February 7, 2010

Handle incoming protobuf messages with IIS Server.

The task is to receive protobuf messages that is sent from client via IIS Server. Of course, you can use native protobuf server to handle incoming request. In my case rest of the application is written using IIS, so I don’t want to cope with additional server process.

Client will send HTTP POST request with content that is protobuf encoded message. IHttpHandler on the other side will be listening for this message on the other side.

To do this, you need to modify web.config:

<configuration>
<httpHandlers>
<add verb="*" path="Device.proto.aspx" validate="false" type="Server.ProtoHttpHandler, Server" />
</httpHandlers>
<!--
The system.webServer section is required for running ASP.NET AJAX under Internet
Information Services 7.0. It is not necessary for previous version of IIS.
-->
<system.webServer>
<handlers>
<add name="ProtoHttpHandler" path="Device.proto" verb="*" type="Server.PrototHttpHandler, Server" resourceType="Unspecified" preCondition="integratedMode" />
</handlers>
</system.webServer>
</configuration>

This will invoke ProtoHttpHandler that can handle incoming message.

public class ProtoHttpHandler : IHttpHandler
{
private UnityContainer _Container;

public ProtoHttpHandler()
{
_Container = new UnityContainer();
}

public void ProcessRequest(HttpContext context)
{
var handler = _Container.Resolve<RequestHandler>();
var decoder = _Container.Resolve<ProtobufEncoder>();
var messages = decoder.Decode(new BinaryReader(context.Request.InputStream).ReadBytes(context.Request.ContentLength));

foreach (var deviceMeasureRequest in messages)
{
handler.OnMeasreRequest(deviceMeasureRequest);
}
context.Response.End();

}

public bool IsReusable
{
get { return true; }
}
}

No comments:

Post a Comment