架构师_程序员_码农网

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

搜索
查看: 7406|回复: 0

[ASP.NET] mvc 用websocket连接不上的错误原因!

[复制链接]
发表于 2016-5-5 15:22:45 | 显示全部楼层 |阅读模式
WebSocket connection to 'ws://localhost:3558/api/Chat' failed: Error during WebSocket handshake: Unexpected response code: 404

js报错!!!!!

前台页面:


  1. @{
  2.     Layout = null;
  3. }

  4. <!DOCTYPE html>

  5. <html>
  6. <head>
  7.     <meta name="viewport" content="width=device-width" />
  8.     <title>Index</title>
  9. </head>
  10. <body>

  11.     <scrip{过滤}t src="/scrip{过滤}t/jquery-1.12.3.min.js"></scrip{过滤}t>
  12.     <scrip{过滤}t type="text/javascrip{过滤}t">
  13.     var ws;
  14.     $(
  15.         function () {
  16.             $("#btnConnect").click(function () {
  17.                 $("#messageSpan").text("Connection...");
  18.                 ws = new WebSocket("ws://" + window.locatio{过滤}n.hostname +":"+window.locatio{过滤}n.port+ "/api/Chat");
  19.                 ws.onopen = function () {
  20.                     $("#messageSpan").text("Connected!");
  21.                 };
  22.                 ws.onmessage = function (result) {
  23.                     $("#messageSpan").text(result.data);
  24.                 };
  25.                 ws.onerror = function (error) {
  26.                     $("#messageSpan").text(error.data);
  27.                 };
  28.                 ws.onclose = function () {
  29.                     $("#messageSpan").text("Disconnected!");
  30.                 };
  31.             });
  32.             $("#btnSend").click(function () {
  33.                 if (ws.readyState == WebSocket.OPEN) {
  34.                     ws.send($("#txtInput").val());
  35.                 }
  36.                 else {
  37.                     $("messageSpan").text("Connection is Closed!");
  38.                 }
  39.             });
  40.             $("#btnDisconnect").click(function () {
  41.                 ws.close();
  42.             });
  43.         }
  44.     );
  45.     </scrip{过滤}t>

  46.     <fieldset>
  47.         <input type="button" value="Connect" id="btnConnect" />
  48.         <input type="button" value="DisConnect" id="btnDisConnect" />
  49.         <hr />
  50.         <input type="text" id="txtInput" />
  51.         <input type="button" value="Send" id="btnSend" />
  52.         <br />
  53.         <span id="messageSpan" style="color:red;"></span>
  54.     </fieldset>
  55. </body>
  56. </html>
复制代码
后台代码:

  1. using System;
  2. using System.Net;
  3. using System.Net.Http;
  4. using System.Net.WebSockets;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using System.Web;
  9. using System.Web.Http;
  10. using System.Web.WebSockets;

  11. namespace ChatRoom.WebUI.Controllers
  12. {
  13.     public class ChatController : ApiController
  14.     {
  15.         public HttpResponseMessage Get()
  16.         {
  17.             if (HttpContext.Current.IsWebSocketRequest)
  18.             {
  19.                 HttpContext.Current.AcceptWebSocketRequest(ProcessWSChat);
  20.             }
  21.             return new HttpResponseMessage(HttpStatusCode.SwitchingProtocols);
  22.         }
  23.         private async Task ProcessWSChat(AspNetWebSocketContext arg)
  24.         {
  25.             WebSocket socket = arg.WebSocket;
  26.             while (true)
  27.             {
  28.                 ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);
  29.                 WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None);
  30.                 if (socket.State == WebSocketState.Open)
  31.                 {
  32.                     string message = Encoding.UTF8.GetString(buffer.Array, 0, result.Count);
  33.                     string returnMessage = "You send :" + message + ". at" + DateTime.Now.ToLongTimeString();
  34.                     buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(returnMessage));
  35.                     await socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
  36.                 }
  37.                 else
  38.                 {
  39.                     break;
  40.                 }
  41.             }
  42.         }
  43.     }
  44. }
复制代码


按理说,应该没错啊!!!!!!!!!

最后,发现是我设置Global.asax中Application_Start顺序的错误,真是日了狗了,下面是正确顺序!!
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. using System.Web.Routing;
  7. using System.Web.Http;

  8. namespace ChatRoom.WebUI
  9. {
  10.     public class MvcApplication : System.Web.HttpApplication
  11.     {
  12.         protected void Application_Start()
  13.         {
  14.             AreaRegistration.RegisterAllAreas();
  15.             GlobalConfiguration.Configure(WebApiConfig.Register);
  16.             RouteConfig.RegisterRoutes(RouteTable.Routes);
  17.             
  18.         }
  19.     }
  20. }
复制代码







上一篇:C# 动态加载Dll接口
下一篇:作为一个初级程序员,做了一个月的winform C/S项目,只是学会复制代码,然后实现
码农网,只发表在实践过程中,遇到的技术难题,不误导他人。
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

免责声明:
码农网所发布的一切软件、编程资料或者文章仅限用于学习和研究目的;不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负。本站信息来自网络,版权争议与本站无关。您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。如有侵权请邮件与我们联系处理。

Mail To:help@itsvse.com

QQ|小黑屋|架构师 ( 鲁ICP备14021824号-2 )|网站地图

GMT+8, 2026-5-9 19:11

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表