Reputation: 3
I start with WebSockets and Node, and my first client not connecting with my server.
Server:
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');
Client:
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
);
};
I have tried everything but did not connect to server. When I try to connect from url 'localhost:9090' it work and back to be 'aaa'. But whet I use my client script it gets an error.
Upvotes: 0
Views: 197
Reputation: 11805
Your server is just an HTTP server. You must use a WebSockets server on top of HTTP server.
The most common way of doing this is to install the package ws
with npm
. You can find the source code and instructions here: https://github.com/websockets/ws
Also, you can use socket.io
. It uses WebSockets along with other methods to allow almost any browser (old and new) to use WebSockets (or a substitute of them). Here you have an example: http://socket.io/get-started/chat/
Upvotes: 1