最近在學習「HTML5遊戲開發實戰」,其中第8章內容是使用WebSocket來構建多人遊戲---《你畫我猜》。然而在實現過程當中,卻一直出錯:html
客戶端請求時,服務器端會報錯並終止:node
而瀏覽器端也會出錯:jquery
服務器代碼:ios
var ws = require(__dirname + '\\lib\\ws\\server'); var server = ws.createServer(); server.addListener("connection",function(conn){ //處理鏈接接入 console.log("A connection established with id",conn.id); var message = "Welcome " + conn.id + " joining the party.Total connection:" + server.manager.length; console.log(message); server.broadcast(message); }); server.listen(8000); console.log("WebSocket server is running."); console.log("Listening to port 8000.");
客戶端代碼:git
var websocketGame = {} $(function(){ if(window['WebSocket']){ //建立鏈接 websocketGame.socket = new WebSocket("ws://localhost:8000"); //處理open事件 websocketGame.socket.onopen = function(e){ console.log('WebSocket connection established.'); }; //處理message事件 websocketGame.socket.onmessage = function(e){ console.log(e.data); }; //處理close事件 websocketGame.socket.onclose = function(e){ console.log('WebSocket connection closed.'); }; } });
各類調bug都無效。而後發現緣由是chrome端的不兼容:github
node-websocket-server,不支持websocket的draft-10,而chrome 14+瀏覽器,只支持draft-10的websocket,這樣chrome基本都不能用了web
由於按書上的教程使用的是node-websocket-server的lib。因此這裏按照這篇教程改爲了WebSocket-Nodeajax
這個工具須要按照兩個環境MVC++和Python2.7 因而選擇使用socket.iochrome
新建兩個文件app.js和index.htmlnpm
app.js
var fs = require('fs') , http = require('http') , socketio = require('socket.io'); var server = http.createServer(function(req, res) { res.writeHead(200, { 'Content-type': 'text/html'}); res.end(fs.readFileSync(__dirname + '/index.html')); }).listen(8000, function() { console.log('Listening at: http://localhost:8000'); }); socketio.listen(server).on('connection', function (socket) { socket.on('message', function (msg) { console.log('Message Received: ', msg); socket.broadcast.emit('message', msg); }); });
index.html:
<html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script src="/socket.io/socket.io.js"></script> <script> $(function(){ var iosocket = io.connect(); iosocket.on('connect', function () { $('#incomingChatMessages').append($('<li>Connected</li>')); iosocket.on('message', function(message) { $('#incomingChatMessages').append($('<li></li>').text(message)); }); iosocket.on('disconnect', function() { $('#incomingChatMessages').append('<li>Disconnected</li>'); }); }); $('#outgoingChatMessage').keypress(function(event) { if(event.which == 13) { event.preventDefault(); iosocket.send($('#outgoingChatMessage').val()); $('#incomingChatMessages').append($('<li></li>').text($('#outgoingChatMessage').val())); $('#outgoingChatMessage').val(''); } }); }); </script> </head> <body> Incoming Chat: <ul id="incomingChatMessages"></ul> <br /> <input type="text" id="outgoingChatMessage"> </body> </html>
而後在當前目錄cmd下: cnpm install socket.io,會在目錄下生成一個文件夾node_modules。
而後用命令:node app.js啓動服務器
這時候打開兩個瀏覽器窗口,就能夠相互聊天了:
參考: