简体   繁体   中英

node.js WebSocket Server

currently i try to create a push server instance for new activities around our database. Of course, you find a lot of information about this topic.

I'm using: http://static.brandedcode.com/nws-docs/#s6-p1

With the following client implementation:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

        <script src="http://cdn.socket.io/stable/socket.io.js"></script>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>

        <title></title>
    </head>
    <body>
        <script type="text/javascript">
            (function() {
                var webSocket = new io.Socket('ws//test', {
                    port: 8080
                });

                webSocket.connect();

                webSocket.on('connect',function() {
                    console.log('Client has connected to the server!');
                });

                webSocket.on('message',function(data) {
                    console.log('Received a message from the server!',data);
                });

                webSocket.on('disconnect',function() {
                    console.log('The client has disconnected!');
                });

                window.ws = webSocket;
            }());
        </script>
    </body>
</html>

The console returns:

Unexpected response code: 404
XMLHttpRequest cannot load http://ws//test:8080/socket.io/xhr-polling//1303822796984. Origin http://test is not allowed by Access-Control-Allow-Origin.
1303822796984GET http://ws//test:8080/socket.io/xhr-polling//1303822796984 undefined (undefined)

I don't know the problem.

Thanks for your help.

Greets!

You´re trying to connect directly to a WebSocket server using Socket.io. If you are running only a WebSocket server and not the Socket.io server, the you can use the normal HTML5 API to connect to websockets.

for example:

var ws = new WebSocket("ws://domain:port");
ws.onopen = function(){}
ws.onmessage = function(m){}
ws.onclose = function(){}

What browser are you using? WebSockets are currently only supported by Google Chrome. Tests in other browsers will fail.

你可能想要'ws://push.xxx.binder.test'而不是'ws//push.xxx.binder.test' (缺少冒号)。

change

var webSocket = new io.Socket('ws//push.xxx.binder.test', {

to

var webSocket = new io.Socket('push.xxx.binder.test', {

You no need to add prefix for your domain for socket.io (especially without colon before slashes). Also var webSocket isn't good naming - socket.io can use not only websockets (even in your errors it using xhr-poliing )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM