c# IIS WebSocket 模块未启用。有关怎么样启用该模块的详细信息

.Net技术 码拜 8年前 (2016-07-12) 2028次浏览
业务需求要用websocket做个功能,本人小白网上搜了个websocket的demo
但连接时就报这个错–“IIS WebSocket 模块未启用。有关怎么样启用该模块的详细信息”
页面代码:
<input type=”button” value=”连接” id=”btnConnect”/>
<input type=”button” value=”断开” id=”btnDisConnect”/>
<hr/>
<input type=”text” id=”txtInput”/>
<input type=”button” value=”发送” id=”btnSend”/>
<br/>
<span id=”messageSpan” style=”color:red;”></span>
<script>
var ws;
$(function () {
$(“#btnConnect”).click(function () {
$(“#messageSpan”).text(“Connection…”);
ws = new WebSocket(“ws://” + window.location.hostname + “:” + window.location.port + “/api/WSChat”);
ws.onopen = function () {
$(“#messageSpan”).text(“Connected!”);
};
ws.onmessage = function (result) {
$(“#messageSpan”).text(result.data);
};
ws.onerror = function (error) {
$(“#messageSpan”).text(error.data);
};
ws.onclose = function () {
$(“#messageSpan”).text(“Disconnected!”);
};
});
$(“#btnSend”).click(function () {
if (ws.readyState == WebSocket.OPEN) {
ws.send($(“#txtInput”).val());
}
else {
$(“messageSpan”).text(“Connection is Closed!”);
}
});
$(“#btnDisconnect”).click(function () {
ws.close();
});
}
);
</script>
后台代码:
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.WebSockets;
namespace StUnityPlatform.Controllers
{
public class WSChatController : ApiController
{
public HttpResponseMessage Get()
{
//if (HttpContext.Current.IsWebSocketRequest)
//{
HttpContext.Current.AcceptWebSocketRequest(ProcessWSChat);
//}
return new HttpResponseMessage(HttpStatusCode.SwitchingProtocols);
}
private async Task ProcessWSChat(AspNetWebSocketContext arg)
{
WebSocket socket = arg.WebSocket;
while (true)
{
ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);
WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None);
if (socket.State == WebSocketState.Open)
{
string message = Encoding.UTF8.GetString(buffer.Array, 0, result.Count);
string returnMessage = “You send :” + message + “. at” + DateTime.Now.ToLongTimeString();
buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(returnMessage));
await socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
}
else
{
break;
}
}
}
}
}
求大大们帮忙,项目是mvc4,后台代码中的if不注释的话就是不进if,HttpContext.Current.IsWebSocketRequest的返回值总是false
解决方案

40

有一个.net 开源的 websocket 服务器 Fleck,你可以看它的例子,编程非常简单。
你可以在本人的console、windows service 甚至 winform、wpf 应用中引用它的 dll(通过 NuGet 安装到工程里即可,不用从网页去下载)。

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明c# IIS WebSocket 模块未启用。有关怎么样启用该模块的详细信息
喜欢 (0)
[1034331897@qq.com]
分享 (0)