首页 > 代码库 > node.js实现WebSocket

node.js实现WebSocket

 最近在学习“HTML5游戏开发实战”,其中第8章内容是使用WebSocket来构建多人游戏---《你画我猜》。然而在实现过程中,却一直出错:

客户端请求时,服务器端会报错并终止:

技术分享

 

而浏览器端也会出错:

技术分享

 

 

服务器代码:

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.");

客户端代码:

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端的不兼容:

node-websocket-server,不支持websocket的draft-10,而chrome 14+浏览器,只支持draft-10的websocket,这样chrome基本都不能用了

 因为按书上的教程使用的是node-websocket-server的lib。所以这里按照这篇教程改成了WebSocket-Node

 这个工具需要按照两个环境MVC++和Python2.7 于是选择使用socket.io

 

新建两个文件app.js和index.html

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:&nbsp;<ul id="incomingChatMessages"></ul><br /><input type="text" id="outgoingChatMessage"></body></html>

然后在当前目录cmd下: cnpm install socket.io,会在目录下生成一个文件夹node_modules。

然后用命令:node app.js启动服务器

这时候打开两个浏览器窗口,就可以相互聊天了:

技术分享

技术分享

 

 

参考:

Nodejs实现websocket的4种方式

Socket.IO 和 Node.js 入门

node.js实现WebSocket