使用前提:
安装nodejs:
为什么需要socket.io?
node.js提供了高效的服务端运行环境,但是由于浏览器端对HTML5的支持不一,为了兼容所有浏览器,提供卓越的实时的用户体验,并且为程序员提供客户端与服务端一致的编程体验,于是socket.io诞生。
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。
socket.io解决了实时的通信问题,并统一了服务端与客户端的编程方式。启动了socket以后,就像建立了一条客户端与服务端的管道,两边可以互通有无。
安装socket.io
npm install socket.io
这里需要注意客户端要使用click文件夹内的文件
服务器端文件
成功安装nodejs后会在系统的path环境变量中自动配置。
var http = require('http'), url = require('url'), fs = require('fs'), server; server = http.createServer(function(req, res){ // your normal server code var path = url.parse(req.url).pathname; switch (path){ case '/': res.writeHead(200, {'Content-Type': 'text/html'}); res.write('<h1>Hello! Try the <a href="/index.html">Socket.io Test</a></h1>'); res.end(); break; case '/index.html': fs.readFile(__dirname + path, function(err, data){ if (err) return send404(res); res.writeHead(200, {'Content-Type': path == 'json.js' ? 'text/javascript' : 'text/html'}) res.write(data, 'utf8'); res.end(); }); break; default: send404(res); } }), send404 = function(res){ res.writeHead(404); res.write('404'); res.end(); }; server.listen(8080); var io = require('socket.io').listen(server); io.sockets.on('connection', function(socket){ console.log("Connection " + socket.id + " accepted."); socket.on('message', function(message){ console.log("Received message: " + message + " - from client " + socket.id); }); socket.on('disconnect', function(){ console.log("Connection " + socket.id + " terminated."); }); socket.on('reconnect',function(){ console.log("reconnect ing terminated."); }); });
启动服务
node server.js
客户端文件
<body> <script> var firstconnect = true; var socket; function connect() { if(firstconnect==true) { socket = io.connect('http://127.0.0.1:8080'); socket.on('message', function(data){ message(data); }); socket.on('connect', function(){ status_update("Connected to Server"); }); socket.on('disconnect', function(){ status_update("Disconnected from Server"); }); socket.on('reconnect', function(){ status_update("Reconnected to Server"); }); socket.on('reconnecting', function( nextRetry ){ status_update("Reconnecting in " + nextRetry + " seconds"); }); socket.on('reconnect_failed', function(){ message("Reconnect Failed"); }); firstconnect = false; } else { socket.reconnect(); } } function disconnect() { socket.disconnect(); } function message(data) { document.getElementById('message').innerHTML = "Server says: " + data; } function status_update(txt){ document.getElementById('status').innerHTML = txt; } function esc(msg){ return msg.replace(/</g, '<').replace(/>/g, '>'); } function send() { socket.send("Hello Server!"); }; </script> <h1>Socket.io Test</h1> <div><p id="status">Waiting for input</p></div> <div><p id="message"></p></div> <button id="connect" onClick='connect()'/>Connect</button> <button id="disconnect" onClick='disconnect()'>Disconnect</button> <button id="send" onClick='send()'/>Send Message</button> </body> </html>
注意要引入socket.io.js文件
界面预览
点击"连接",再点击发送消息。就能在nodejs的命令行窗口看到接收到的消息了。
简易的sock.io便搭建完成。
具体实施还可以发送到指定用户,群发。等功能。
-----------------------------------------------------
转载请注明来源此处
原地址:#
发表