一 问题描述
利用以往开发的单机桌面应用程序,将其转换成网络服务,可以避免资源浪费!
二 创建后台应用
1)创建一个控制台应用
2)添加引用(WebSockets引用在.net framework 4.7.2版本以下可能不支持)
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Cors;
using System.Web.Http.SelfHost;
添加这些引用可以在下面的链接找到:
https://www.nuget.org/
3)分配一个空的端口号,设置服务器的地址。
4)配置HttpSelfHostServer,可以设置前端、后台的传输限制。
5)注册CORS
public static void Register(HttpConfiguration config)
{
// 配置和启用 CORS
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
}
6)配置路由
// 设置路由
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}");
7)创建服务
using (var server = new HttpSelfHostServer(config))
{
// 启动监听
server.OpenAsync().Wait();
RunWebSocketServer("http://localhost:5000/").GetAwaiter().GetResult();
Console.WriteLine("服务正在运行..."); //监听后台
Console.ReadLine();
}
8)到此创建好了一个后台服务,然后创建API接口,将其命名为HomeController
9)添加引用,在HomeController中添加以下引用
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.IO.Compression;
using System.Data;
using System.Text;
using System.Web;
using System.Net.WebSockets;
using System.Web.WebSockets;
using System.Threading;
10)编写一个API实例,并在浏览器上访问。
11)启动服务(此时还是本机服务)(请使用管理员启动编译器)
12)测试成功!
13)将本机服务发布到公网,可以利用内网穿透工具,这个不详细介绍了。
到此我们成功创建了一个简单的后台服务了!
三 附件
创建服务所需要的函数,如下代码:
public static async Task RunWebSocketServer(string url)
{
HttpListener httpListener = new HttpListener();
httpListener.Prefixes.Add(url);
httpListener.Start();
Console.WriteLine("Listening...");
while (true)
{
HttpListenerContext httpListenerContext = await httpListener.GetContextAsync();
if (httpListenerContext.Request.IsWebSocketRequest)
{
HttpListenerWebSocketContext webSocketContext = null;
try
{
webSocketContext = await httpListenerContext.AcceptWebSocketAsync(subProtocol: null);
WebSocket webSocket = webSocketContext.WebSocket;
Console.WriteLine("Connected!");
await HandleWebSocketAsync(webSocket);
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
httpListenerContext.Response.StatusCode = 500;
httpListenerContext.Response.Close();
}
}
else
{
httpListenerContext.Response.StatusCode = 400;
httpListenerContext.Response.Close();
}
}
}
private static async Task HandleWebSocketAsync(WebSocket webSocket)
{
byte[] buffer = new byte[1024 * 4];
WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
while (!result.CloseStatus.HasValue)
{
await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);
result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
}
await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
}