首页 新闻 会员 周边

Error during WebSocket handshake: 'Connection' header is missing

0
悬赏园豆:50 [已关闭问题] 关闭于 2017-06-16 00:01

在进行使用websocket第一次握手的时候,出现了Error during WebSocket handshake: 'Connection' header is missing错误。

服务调试的时候确实少了但是我在程序上确实加了,具体代码如下:

using System;
using System.Collections.Specialized;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace ConsoleApplication2 {

    internal class Program {

        private static void Main(string[] args) {
            HttpListener listener = new HttpListener();
            listener.Prefixes.Add("http://localhost:8089/"); //要监听的url范围
            listener.Start();   //开始监听端口,接收客户端请求
            Console.WriteLine("Listening");
            try {
                while (true) {
                    //获取一个客户端请求为止
                    HttpListenerContext context = listener.GetContext();
                    //将其处理过程放入线程池
                    System.Threading.ThreadPool.QueueUserWorkItem(ProcessHttpClient, context);
                }
            }
            catch (Exception e) {
                Console.WriteLine(e.Message);
            }
            finally {
                listener.Stop();    //关闭HttpListener
            }
        }

        //客户请求处理
        private static void ProcessHttpClient(object obj) {
            HttpListenerContext context = obj as HttpListenerContext;
            HttpListenerRequest request = context.Request;
            HttpListenerResponse response = context.Response;
            if (IsUpgradeTo(request, "websocket")) {
                response.StatusCode = 101;
                response.Headers["Connection"] = "Upgrade";
                response.Headers["Upgrade"] = "websocket";
                string _base64Key = request.Headers["Sec-WebSocket-Key"];
                response.Headers["Sec-WebSocket-Accept"] = SocketHelper.CreateResponseKey(_base64Key);
                if (request.Headers["Sec-WebSocket-Protocol"] != null) {
                    response.Headers["Sec-WebSocket-Protocol"] = request.Headers["Sec-WebSocket-Protocol"];
                }
                if (request.Headers["Sec-WebSocket-Version"] != null)
                    response.Headers["Sec-WebSocket-Version"] = request.Headers["Sec-WebSocket-Version"];
                if (request.Headers["Sec-WebSocket-Extensions"] != null)
                    response.Headers["Sec-WebSocket-Extensions"] = request.Headers["Sec-WebSocket-Extensions"];
            }
            else {

            }
            //do something as you want
            string responseString = string.Format("<HTML><BODY> {0}</BODY></HTML>", DateTime.Now);
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
            response.ContentLength64 = buffer.Length;
            System.IO.Stream output = response.OutputStream;
            output.Write(buffer, 0, buffer.Length);
            output.Flush();
            //关闭输出流,释放相应资源
            output.Close();
        }

        public static bool IsUpgradeTo(HttpListenerRequest request, string protocol) {
            if (request == null)
                throw new ArgumentNullException("request");

            if (protocol == null)
                throw new ArgumentNullException("protocol");

            if (protocol.Length == 0)
                throw new ArgumentException("An empty string.", "protocol");
            return Contains(request.Headers, "Upgrade", protocol) && Contains(request.Headers, "Connection", "Upgrade");
        }

        public static bool Contains(NameValueCollection collection, string name, string value) {
            if (collection == null || collection.Count == 0)
                return false;

            var vals = collection[name];
            if (vals == null)
                return false;

            foreach (var val in vals.Split(','))
                if (val.Trim().Equals(value, StringComparison.OrdinalIgnoreCase))
                    return true;

            return false;
        }
    }
}

 

客户端调用代码

<!DOCTYPE html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <script src="~/Scripts/jquery-1.8.2.min.js"></script>
    <script>
        var ws;
        $().ready(function () {
            $('#conn').click(function () {
                //ws = new WebSocket('ws://' + window.location.hostname + ':' + '4649/Echo/');
                ws = new WebSocket('ws://' + window.location.hostname + ':' + '8089');
                $('#tips').text('正在连接');
                ws.onopen = function () {
                    $('#tips').text('已经连接');
                }
                ws.onmessage = function (evt) {
                    $('#tips').text(evt.data);
                }
                ws.onerror = function (evt) {
                    $('#tips').text(JSON.stringify(evt));
                }
                ws.onclose = function () {
                    $('#tips').text('已经关闭');
                }
            });

            $('#close').click(function () {
                ws.close();
            });

            $('#send').click(function () {
                if (ws.readyState == WebSocket.OPEN) {
                    ws.send($('#content').val());
                }
                else {
                    $('#tips').text('连接已经关闭');
                }
            });

        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>

            <input id="conn" type="button" value="连接" />
            <input id="close" type="button" value="关闭" />
            <span id="tips"></span>
            <input id="content" type="text" />
            <input id="send" type="button" value="发送" />
        </div>
    </form>
</body>

 

希望各位帮忙看看到底是为什么?由于不允许使用4.5的frame框架,只能使用4.0及以下的框架。

yjq_net的主页 yjq_net | 初学一级 | 园豆:2
提问于:2016-04-06 16:41
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册