使用MVC控制器与websockets连接到windowsazure

Connecting with websockets to windows azure using MVC controller

本文关键字:连接 windowsazure websockets MVC 控制器 使用      更新时间:2023-09-26

我试图在这里做这个例子: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>

正如你所看到的,我一直在尝试使用跟踪来找出错误所在。跟踪"Inside IsWebSocketRequest check"被记录,但DoTalking方法内部的跟踪没有。

当我尝试运行它时,我会收到"基础连接已关闭"的消息。azure上的此网站已启用Web套接字。我不知道端口,但由于我在mvc中使用控制器,我认为端口80应该是默认的。我的老师很快看了一眼,不明白问题出在哪里。

任何帮助或指示都将不胜感激!

将Index方法中的最后一行替换为return new HttpStatusCodeResult(HttpStatusCode.SwitchingProtocols);

public ActionResult Index()
{
    if (ControllerContext.HttpContext.IsWebSocketRequest)
    {
        Trace.WriteLine("Inside IsWebSocketRequest check");
        ControllerContext.HttpContext.AcceptWebSocketRequest(DoTalking);
    }
    return new HttpStatusCodeResult(HttpStatusCode.SwitchingProtocols);
}