Original digest self of front-end blog, welcome everyone to visitHttp://hacke2.github.io
Brief introduction
Recently saw node. js and HTML5, practiced hand a simple version of the chat demo, entertainment
Why do I need Socket.io?
node. JS provides an efficient server-side runtime environment, but thanks to the browser-side support for HTML5, the Socket.io was born to provide a superior real-time user experience for all browsers, and to provide programmers with a consistent programming experience for the client and server.
简答来说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以后,就像建立了一条客户端与服务端的管道,两边可以互通有无。
Code
Create App.js source code as follows
var FS = require(' FS ')//File Operations , http = require(' http ')//http Server , Socketio = require(' Socket.io ');//socket.io, used to interact with the foreground var Server = http.Createserver(function(req, Res) { Res.Writehead( $, { ' Content-type ': ' text/html '}); //index.html output Res.End(FS.Readfilesync(__dirname + '/index.html '));}).Listen( the, function() { Console.Log(' Listening at:http://localhost:3000 ');});//Connection succeeded callbackSocketio.Listen(Server). on(' Connection ', function (Socket) { Socket. on(' message ', function (msg) { Console.Log(' to receive ', msg); //Send information to other clients Socket.Broadcast.Emit(' message ', msg); });});
Create index.html
<meta charset="Utf-8"> <scriptsrc="Http://libs.baidu.com/jquery/1.9.0/jquery.js"></script> <scriptsrc="/socket.io/socket.io.js"></script> <script> $(function(){ var Iosocket = io.Connect(); Iosocket. on(' Connect ', function () { $(' #incomingChatMessages ').Append($(' <li> is connected! </li> ')); Iosocket. on(' message ', function(message) { $(' #incomingChatMessages ').Append($(' <li></li> ').text(message)); }); Iosocket. on(' Disconnect ', function() { $(' #incomingChatMessages ').Append(' <li> lost connection </li> '); }); }); $(' #outgoingChatMessage ').KeyPress(function(Event) { if(Event.which == -) { Event.Preventdefault(); Iosocket.Send($(' #outgoingChatMessage ').Val()); $(' #incomingChatMessages ').Append($(' <li></li> ').text($(' #outgoingChatMessage ').Val())); $(' #outgoingChatMessage ').Val("'); } }); }); </script><body>Console: <ul id="Incomingchatmessages"></ul><br /><input type="Text" id="Outgoingchatmessage"></body>
Run & Results
Because it relies on the Socket.io package, we use NPM to download
NPM Install Socket.io
Last Run directly
Node App.js
Run effect
Attached a very bright chat demo http://segmentfault.com/a/1190000000479518
Chat Demo
End from Http://hacke2.github.io
Chat demo for WebSocket based on node. js + Socket.io