使用MVC控制器将WebSocket连接到Windows Azure [英] Connecting with websockets to windows azure using MVC controller

查看:80
本文介绍了使用MVC控制器将WebSocket连接到Windows Azure的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在此处进行示例: http://www.codeguru .com/csharp/csharp/programming-html5-web-sockets-in-asp.net-4.5.htm (但有一点曲折,我使用MVC控制器作为建立Web套接字连接的门)

I'm trying to do the example here: http://www.codeguru.com/csharp/csharp/programming-html5-web-sockets-in-asp.net-4.5.htm (but with a little twist, I use an MVC controller as the gate for establishing a web socket connection)

这是我在mvc4中的控制器:

This is my controller in 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;
            }
        }
    }


}

这是我尝试联系的观点:

This is my view from which I try to connect:

 <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>

如您所见,我一直在尝试使用trace找出错误所在.记录了"Inside IsWebSocketRequest检查"跟踪,但没有记录DoTalking方法内部的跟踪.

As you can see I've been trying to use trace to find out wher the error is. The trace "Inside IsWebSocketRequest check" is logged but the trace inside the DoTalking method is not.

当我尝试运行它时,收到底层连接已关闭"消息. Azure上为此网站启用了Web套接字.我不知道端口,但是因为我在mvc中使用控制器,所以我想端口80应该仍然是默认端口.我的老师快速浏览了一下,却不知道是什么问题.

I get the "The underlying connection is closed" message when I try to run it. Web sockets is enabled for this web site on azure. I dont know the port but then since I am using a controller in mvc I figured port 80 should be the default anyway. My teacher took a quick look at this and couldn't figure out what the problem was.

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

Any help or pointer would be appreciated!

推荐答案

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

Replace the last line in Index method to 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);
}

这篇关于使用MVC控制器将WebSocket连接到Windows Azure的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆