我刚刚交了一个新项目,大部分工作已经完成,但我需要为项目更改一些内容。我在consoleapp中有一个这样的自托管服务器设置:
using (var server = new HttpSelfHostServer(config))
{
server.OpenAsync().Wait();
Console.WriteLine("Press enter to exit");
Console.ReadLine();
}
和这样配置的路线:
private static HttpSelfHostConfiguration CreateWebServerConfiguration()
{
var config = new HttpSelfHostConfiguration(string.Format("http://{0}:{1}", Environment.MachineName, 80));
config.Routes.MapHttpRoute("Api", "api/{controller}/{id}/{value}", new {id = RouteParameter.Optional, value = RouteParameter.Optional });
config.Routes.MapHttpRoute("Defect", "defect/{action}/{id}", new { controller = "Defect", action = RouteParameter.Optional, id = RouteParameter.Optional });
config.Routes.MapHttpRoute("Content", "content/{action}/{file}", new { controller = "Content"});
config.Routes.MapHttpRoute("Default", "{controller}/{action}/{id}/{date}", new { controller = "Home", action = "Index", id = RouteParameter.Optional, date = RouteParameter.Optional });
var templateConfig = new TemplateServiceConfiguration { Resolver = new DelegateTemplateResolver(name => ReadFileContent("Views", name))};
Razor.SetTemplateService(new TemplateService(templateConfig));
return config;
}
这很好用,但我遇到了一种情况,我不希望前端用服务器上的计时器拉(当前每5分钟自动刷新一次)。当需要更新新内容时,我希望服务器更新前端。我找到了解决方案,这将是websockets,但我有很多问题使用它们。
我的.js文件:
(function() {
if ("WebSocket" in window) {
alert("WebSocket is supported by your Browser!");
} ws://' + window.location.hostname + window.location.pathname.replace('index.htm', 'ws.ashx') + '?name='
var socket = new WebSocket("ws://localhost:80/WebsocketServer.cs");
socket.onmessage = function(event) {
alert("message recv.");
alert(event.data);
};
socket.onopen = function() {
alert("open");
}
socket.onerror = function(errorEvent) {
alert("Error");
alert(errorEvent);
};
socket.onclose = function(closeEvent) {
alert(closeEvent.code);
}
})();
我找到了多个像这样的例子:https://blog.simpleisbest.co.uk/2012/05/01/websockets-with-asp-net-4-5-and-visual-studio-11/但它似乎对我不起作用,这是我的文件:
WebsocketServer.cs
public class WebsocketServer : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.IsWebSocketRequest)
{
context.AcceptWebSocketRequest(new WebSocketManager());
}
}
public bool IsReusable
{
get { return false; }
}
}
WebSocketManager.cs
public class WebSocketManager : WebSocketHandler
{
public static WebSocketCollection clients = new WebSocketCollection();
public override void OnClose()
{
clients.Remove(this);
}
public override void OnError()
{
}
public override void OnMessage(string message)
{
}
public override void OnOpen()
{
clients.Add(this);
clients.Broadcast("Connected");
}
}
前端返回结束代码1006或CLOSE_ABNORMAL。我的猜测是没有创建后端的链接?