This simple web socket example正在返回 200 错误。
编辑:我正在用 C# 重新发布代码,希望更多人能够就我遇到此问题的原因向我提出建议。
我在本地 IIS 机器上运行 VS2012 Express,项目配置为 4.5.1 框架,我导入了 Nuget Microsoft.Websockets 包。
我在下面包含的三段代码是项目中仅有的三段代码,我没有对项目的其余部分进行任何修改。
在意外错误之前没有中断,它不会在任何一方打开或消息时中断。 200 在 Chrome 控制台中显示为错误,但没有响应预览。
这是客户端(index.htm):
<!doctype html>
<html>
<head>
<title></title>
<script src="Scripts/jquery-1.8.1.js" type="text/javascript"></script>
<script src="test.js" type="text/javascript"></script>
</head>
<body>
<input id="txtMessage" />
<input id="cmdSend" type="button" value="Send" />
<input id="cmdLeave" type="button" value="Leave" />
<br />
<div id="chatMessages" />
</body>
</html>
和客户端脚本(test.js):
$(document).ready(function () {
var name = prompt('what is your name?:');
var url = 'ws://' + window.location.hostname + window.location.pathname.replace('index.htm', 'ws.ashx') + '?name=' + name;
alert('Connecting to: ' + url);
var ws = new WebSocket(url);
ws.onopen = function () {
$('#messages').prepend('Connected <br/>');
$('#cmdSend').click(function () {
ws.send($('#txtMessage').val());
$('#txtMessage').val('');
});
};
ws.onmessage = function (e) {
$('#chatMessages').prepend(e.data + '<br/>');
};
$('#cmdLeave').click(function () {
ws.close();
});
ws.onclose = function () {
$('#chatMessages').prepend('Closed <br/>');
};
ws.onerror = function (e) {
$('#chatMessages').prepend('Oops something went wrong<br/>');
};
});
这是通用处理程序 (ws.ashx):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Web.WebSockets;
namespace WebSockets
{
public class ws : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.IsWebSocketRequest)
context.AcceptWebSocketRequest(new TestWebSocketHandler());
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
这是类 (TestWebSocketHandler):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using Microsoft.Web.WebSockets;
namespace WebSockets
{
public class TestWebSocketHandler : WebSocketHandler
{
private static WebSocketCollection clients = new WebSocketCollection();
private string name;
public override void OnOpen()
{
this.name = this.WebSocketContext.QueryString["name"];
clients.Add(this);
clients.Broadcast(name + " has connected.");
}
public override void OnMessage(string message)
{
clients.Broadcast(string.Format("{0} said: {1}", name, message));
}
public override void OnClose()
{
clients.Remove(this);
clients.Broadcast(string.Format("{0} has gone away.", name));
}
}
}
最佳答案
它没有针对此问题的任何影响提出错误,但我发现 Chrome 无法返回我的 200 响应的错误。
我只需在控制面板 --> 程序 --> 打开或关闭 Windows 功能 --> IIS --> 应用程序开发功能 --> WebSocket 协议(protocol)下打开 WebSocket 协议(protocol)。
至少我已经向站点添加了一个简单的 VB.NET WebSocket。
只需确保您拥有 IIS 7+ 并在 4.5 Framework 中运行 Windows 8...并打开上面的 WebSocket 功能。
关于c# - .NET 网络套接字返回 200 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18902546/