node.js實現WebSocket

來源:互聯網
上載者:User

標籤:

 最近在學習“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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.