【发布时间】:2013-12-06 05:16:58
【问题描述】:
我正在尝试在这里做示例: http://www.codeguru.com/csharp/csharp/programming-html5-web-sockets-in-asp.net-4.5.htm(但稍加改动,我使用 MVC 控制器作为建立 Web 套接字连接的门)
这是我在 mvc4 中的控制器:
public class HandleWSController : Controller
{
//
// GET: /HandleWS/
public ActionResult Index()
{
if (ControllerContext.HttpContext.IsWebSocketRequest)
{
Trace.WriteLine("Inside IsWebSocketRequest check");
ControllerContext.HttpContext.AcceptWebSocketRequest(DoTalking);
}
return View();
}
public async Task DoTalking(AspNetWebSocketContext context)
{
Trace.WriteLine("Inside DoTalking");
WebSocket socket = context.WebSocket;
while (true)
{
var buffer = new ArraySegment<byte>(new byte[1024]);
WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None);
Trace.WriteLine("Result: " + result.ToString());
Trace.WriteLine("State: " + socket.State.ToString());
if (socket.State == WebSocketState.Open)
{
string userMessage = Encoding.UTF8.GetString(buffer.Array, 0, result.Count);
userMessage = "You sent: " + userMessage + " at " + DateTime.Now.ToLongTimeString();
Trace.WriteLine(userMessage);
buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(userMessage));
await socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
}
else
{
break;
}
}
}
}
这是我尝试连接的视图:
<h2>Index</h2>
<input type="text" id="txtMsg" placeholder="Write your message here" /><input type="submit" id="btnSend" value="Send" /><input type="submit" id="btnStop" value="Stop" />
<div id="divHistory">
</div>
<script>
var socket;
$(document).ready(function () {
socket = new WebSocket("ws://wstester.azurewebsites.net/HandleWS/Index");
socket.onopen = function (evt) {
$("#divHistory").html('<h3>Connection Opened with the Echo server.</h3> ');
}
socket.onmessage = function (evt) {
$("#divHistory").html('<h3>' + evt.data + '</h3> ');
}
socket.onerror = function (evt) {
$("#divHistory").html('<h3>Unexpected Error.</h3> ');
}
});
$("#btnSend").click(function () {
if (socket.readyState == WebSocket.OPEN) {
socket.send($("#txtMsg").val());
}
else {
$("#divHistory").append('<h3>The underlying connection is closed.</h3> ');
}
});
$("#btnStop").click(function () {
socket.close();
});
</script>
如您所见,我一直在尝试使用跟踪来找出错误所在。跟踪“IsWebSocketRequest 内部检查”已记录,但 DoTalking 方法内部的跟踪未记录。
我在尝试运行它时收到“底层连接已关闭”消息。在 azure 上为此网站启用了 Web 套接字。我不知道端口,但是因为我在 mvc 中使用控制器,所以我认为端口 80 应该是默认端口。我的老师快速浏览了一下,无法弄清楚问题所在。
任何帮助或指针将不胜感激!
【问题讨论】:
-
您希望我在这个问题中添加什么,缺少什么?
标签: c# javascript jquery azure websocket