基於Node.js + socket.io實現WebSocket的聊天DEMO

來源:互聯網
上載者:User

標籤:android   style   http   color   io   os   java   ar   for   

原文摘自我的前端部落格,歡迎大家來訪問http://hacke2.github.io

簡介

最近看Node.js和HTML5,練手了一個簡易版的聊天DEMO,娛樂一下

為什麼需要socket.io?

node.js提供了高效的服務端運行環境,但是由於瀏覽器端對HTML5的支援不一, 為了相容所有瀏覽器,提供卓越的即時的使用者體驗,並且為程式員提供用戶端與服務端一致的編程體驗, 於是socket.io誕生。

簡答來說socket.io具體以下特點:1.socket.io設計的目標是支援任何的瀏覽器,任何Mobile裝置。目前支援主流的PC瀏覽器 (IE,Safari,Chrome,Firefox,Opera等),Mobile瀏覽器(iphone Safari/ipad Safari/android WebKit/WebOS WebKit等)。socket.io基於node.js並簡化了WebSocket API,統一了通訊的API。它支援:WebSocket, Flash Socket, AJAX long-polling, AJAX multipart streaming, Forever IFrame, JSONP polling。2.socket.io解決了即時的通訊問題,並統一了服務端與用戶端的編程方式。啟動了socket以後,就像建立了一條用戶端與服務端的管道,兩邊可以互連有無。
代碼

建立app.js 源碼如下

var fs = require(‘fs‘)//檔案操作    , http = require(‘http‘)//http伺服器    , socketio = require(‘socket.io‘);//socket.io,用來和前台進行互動  var server = http.createServer(function(req, res) {    res.writeHead(200, { ‘Content-type‘: ‘text/html‘});    //將index.html輸出    res.end(fs.readFileSync(__dirname + ‘/index.html‘));}).listen(3000, function() {    console.log(‘Listening at: http://localhost:3000‘);});//串連成功的回調  socketio.listen(server).on(‘connection‘, function (socket) {    socket.on(‘message‘, function (msg) {        console.log(‘接受到 ‘, msg);        //將資訊發送給其他用戶端        socket.broadcast.emit(‘message‘, msg);    });});

建立index.html

<html><head><meta charset="utf-8">    <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>    <script src="/socket.io/socket.io.js"></script>    <script>        $(function(){            var iosocket = io.connect();              iosocket.on(‘connect‘, function () {                $(‘#incomingChatMessages‘).append($(‘<li>已串連!</li>‘));                  iosocket.on(‘message‘, function(message) {                    $(‘#incomingChatMessages‘).append($(‘<li></li>‘).text(message));                });                iosocket.on(‘disconnect‘, function() {                    $(‘#incomingChatMessages‘).append(‘<li>失去串連</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>控制台:&nbsp;<ul id="incomingChatMessages"></ul><br /><input type="text" id="outgoingChatMessage"></body></html>
運行&結果

因為依賴了socket.io包,所以用npm 下載

npm install socket.io

最後直接運行

node app.js

運行效果

附上一個實現了很炫聊天DEMO http://segmentfault.com/a/1190000000479518

聊天DEMO

end from http://hacke2.github.io

基於Node.js + socket.io實現WebSocket的聊天DEMO

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.