net:尝试建立连接时ERR_CONNECTION_REFUSED

时间:2016-05-01 19:41:00

标签: javascript asp.net websocket

我一直在使用asp.net和一些javascript制作聊天系统的一些教程,但我遇到了问题。该项目工作正常,直到它尝试创建websocket。而不是创建它并继续前进只是给了我错误:

  

失败:连接建立错误:net:ERR_CONNECTION_REFUSED

我现在一直试图解决这个问题大约3个小时,但我没有运气。我尝试过使用xampp并运行apache,但它还没有工作。这是我的代码: 的index.html:

<!doctype html>
<html>
<head>

    <script src="Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>

    <script type="text/javascript">

        $(document).ready(function () {

        var name = prompt('what is your name?:');

        var url = 'ws://' + window.location.hostname + window.location.pathname.replace('index.html', 'ws.ashx') + '?name=' + name;

        alert('Connecting to: ' + url);

        ws = new WebSocket(url);

        ws.onopen = function () {

        $('#messages').prepend('Connected <br/>');

        $('#cmdSend').click(function () {

        ws.send($('#txtMessage').val());

        $('#txtMessage').val('');

        });

        };

        ws.onmessage = function (e) {

        $('#chatMessages').prepend(e.data + '<br/>');

        };

        $('#cmdLeave').click(function () {

        ws.close();

        });

        ws.onclose = function () {

        $('#chatMessages').prepend('Closed <br/>');

        };

        ws.onerror = function (e) {

        $('#chatMessages').prepend('Oops something went wront <br/>');

        };

        });

    </script>

</head>

<body>

    <input id="txtMessage" />

    <input id="cmdSend" type="button" value="Send" />

    <input id="cmdLeave" type="button" value="Leave" />

    <br />

    <div id="chatMessages" />

</body>

</html>

ws.ashx:

public class WSHttpHandler:IHttpHandler

    {

        public void ProcessRequest(HttpContext context)

        {

            if (context.IsWebSocketRequest)

            context.AcceptWebSocketRequest(new TestWebSocketHandler());

        }

        public bool IsReusable

        {

            get

            {

            return false;

            }

        }

    }

和TestWebSocketHandler.cs:

    public class TestWebSocketHandler : WebSocketHandler

    {

        private static WebSocketCollection clients = new WebSocketCollection();

        private string name;

        public override void OnOpen()

        {

            this.name = this.WebSocketContext.QueryString["name"];

            clients.Add(this);

            clients.Broadcast(name + " has connected.");

        }

        public override void OnMessage(string message)

        {

            clients.Broadcast(string.Format("{0} said: {1}", name, message));

        }

        public override void OnClose()

        {

            clients.Remove(this);

            clients.Broadcast(string.Format("{0} has gone away.", name));

        }

    }

0 个答案:

没有答案