说明
HttpService是Http系服务器基类,但是不参与实际的数据交互,实际的数据交互由HttpSocketClient完成,所以HttpService的功能只是配置、激活、管理、注销、重建HttpSocketClient类实例。
可配置项
支持插件接口
声明自定义实例类,然后实现IHttpPlugin接口,即可实现下列事务的触发。
或者继承自HttpPluginBase类,重写相应方法即可。
IHttpPlugin
OnDelete | 当收到Delete请求时 |
OnGet | 当收到OnGet请求时 |
OnPost | 当收到OnPost请求时 |
OnPut | 当收到OnPut请求时 |
OnReceivedOtherHttpRequest | 当收到OnReceivedOtherHttpRequest请求时 |
创建HttpService
HttpService的创建,基本和TcpService一致,也可以通过继承实现,下列仅演示最简单实现。
HttpService的相关事务,会通过插件触发。
var service = new HttpService();
var config = new RRQMConfig();
config.UsePlugin()
.SetReceiveType(ReceiveType.Auto)
.SetListenIPHosts(new IPHost[] { new IPHost(7789) });
service.Setup(config).Start();
service.AddPlugin<MyHttpPlug>();
Console.WriteLine("Http服务器已启动");
在插件中,通过重写(或实现)的方式,进入OnGet、OnPost、OnDelete、OnPut等函数,即可处理对应请求。
其中,通过e参数获得:
- e.Request:Http请求,可以获得一些请求信息。
- e.Response:Http响应,默认是null,如果需要响应,直接构造HttpResponse,然后赋值即可。
/// <summary>
/// 支持GET、Post、Put,Delete,或者其他
/// </summary>
class MyHttpPlug : HttpPluginBase
{
protected override void OnGet(ITcpClientBase client, HttpContextEventArgs e)
{
Console.WriteLine(e.Request.ToString());
////构建响应
//HttpResponse response = new HttpResponse();
//response.FromText("RRQM");
////对当前请求作出响应,在该事件结束后回应。
//e.Response = response;
////或者直接构建响应,然后发送。
//using (ByteBlock byteBlock=new ByteBlock())
//{
// response.Build(byteBlock);
// client.DefaultSend(byteBlock);//使用DefaultSend发送能够完全怕排除适配器影响。
//}
base.OnGet(client, e);
}
protected override void OnReceivedOtherHttpRequest(ITcpClientBase client, HttpContextEventArgs e)
{
Console.WriteLine(e.Request.ToString());
base.OnReceivedOtherHttpRequest(client, e);
}
}
创建HttpsService
Https服务器,和http服务器几乎一样,只不过增加了一个Ssl的配置。
.SetServiceSslOption(new ServiceSslOption()
{
Certificate = new X509Certificate2("RRQMSocket.pfx", "RRQMSocket"),
SslProtocols = SslProtocols.Tls12
}))