Javascript WebSocket未连接

时间:2016-06-18 18:29:41

标签: javascript node.js websocket client

我从WebSockets和Node开始,我的第一个客户端没有连接我的服务器。

服务器:

var http = require('http');
var onRequest = function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('aaaaa\n');
}
http.createServer(onRequest).listen(9090, '127.0.0.1');

客户端:

window.onload = function() {
    var canvasHandle = false;
    var bufferHandle = false;
    var bufferImage = false;
    var WIDTH = 400;
    var HEIGHT = 400;
    var lastTime = false;
    var currentTime = false;
    var dt = false;
    var unitStep = 2;

    var unitX = new Object();
        unitX.name = "John"; 
        unitX.x = 10;
        unitX.y = 10;
        unitX.bodyWidth = 20;
        unitX.bodyHeight = 20;
        unitX.bodyColor = "rgb(0,0,255)";

    var update = function(dt) {
    }
    var draw = function() {
        //Clear Buffer
        bufferHandle.fillStyle = "rgb(200,200,200)";
        bufferHandle.beginPath();
        bufferHandle.rect(0, 0, WIDTH, HEIGHT);
        bufferHandle.fill();

        //Draw Objects

        bufferHandle.fillStyle = unitX.bodyColor;
        bufferHandle.beginPath();
        bufferHandle.rect(unitX.x, unitX.y, unitX.bodyWidth, unitX.bodyHeight);
        bufferHandle.fill();

        //Double Buffer
        bufferImage = bufferHandle.getImageData(0,0,WIDTH,HEIGHT);
        canvasHandle.putImageData(bufferImage,0,0);
    }
    var gameLoop = function(){
        currentTime = new Date();
        elapsedTime = currentTime.getTime() - lastTime.getTime();

        update(elapsedTime);
        draw();

        lastTime = currentTime;
    }

    $(document).keypress(function(evt){

        switch(evt.which){
            case 100: //d
                unitX.x += unitStep;
                break;
            default:
                //alert(evt.which);
        }
    });

    var socket = new WebSocket("ws://127.0.0.1:9090/");

    socket.onerror = function(error) {
        alert('Error');
    };
    socket.onopen = function(event) {
        alert('Connected');
    };
    socket.onmessage = function(event) {

    };
    socket.onclose = function(event) {

    };
    //Create Canvas 
    bufferHandle = document.createElement('canvas');
    bufferHandle.width = WIDTH;
    bufferHandle.height = HEIGHT;
    bufferHandle = bufferHandle.getContext('2d');

    canvasHandle = document.getElementById('game');
    canvasHandle = canvasHandle.getContext('2d');
    lastTime = new Date();
    setInterval(
        function(){
            gameLoop();
        }, 50
    );

};

我已尝试过所有内容但未连接到服务器。当我尝试连接url' localhost:9090'它的工作和回归是' aaa'。但是,当我使用我的客户端脚本时,它会出错。

1 个答案:

答案 0 :(得分:1)

您的服务器只是一个HTTP服务器。您必须在HTTP服务器上使用WebSockets服务器。

最常见的方法是使用ws安装包npm。您可以在此处找到源代码和说明:https://github.com/websockets/ws

此外,您可以使用socket.io。它使用WebSockets和其他方法,几乎​​允许任何浏览器(旧的和新的)使用WebSockets(或替代它们)。这里有一个例子:http://socket.io/get-started/chat/