使用MVC控制器将websockets连接到windows azure

时间:2013-11-21 16:06:42

标签: c# javascript jquery azure websocket

我正在尝试这里的例子: 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应该是默认的。我的老师快速浏览了一下,无法弄清问题是什么。

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

1 个答案:

答案 0 :(得分:0)

将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);
}