socket.io安装部署
Posted 潜台词
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了socket.io安装部署相关的知识,希望对你有一定的参考价值。
需要node.js环境
创建package.json
npm init
下载相关依赖
npm install --save express@4.10.2
npm会在当前目录下载所需要的依赖到node_modules的文件夹中
下载安装socket.io
npm install -save socket.io
事例
服务端示例:
1 var app = require(\'express\')(); 2 var http = require(\'http\').Server(app); 3 var io = require(\'socket.io\')(http); 4 5 //app.get(\'/\', function(req, res){ 6 // res.send(\'<h1>Hello world</h1>\'); 7 //}); 8 9 /*app.get(\'/\', function(req, res){ 10 res.sendFile(__dirname + \'/index.html\'); 11 }); 12 */ 13 14 app.get(\'/\', function(req, res){ 15 res.sendfile(\'index.html\'); 16 }); 17 18 /*io.on(\'connection\', function(socket){ 19 console.log(\'a user connected\'); 20 }); 21 22 io.on(\'connection\', function(socket){ 23 console.log(\'a user connected\'); 24 socket.on(\'disconnect\', function(){ 25 console.log(\'user disconnected\'); 26 }); 27 }); 28 29 io.on(\'connection\', function(socket){ 30 socket.on(\'chat message\', function(msg){ 31 console.log(\'message: \' + msg); 32 }); 33 });*/ 34 35 36 io.on(\'connection\', function(socket){ 37 socket.on(\'chat message\', function(msg){ 38 io.emit(\'chat message\', msg); 39 }); 40 }) 41 42 43 http.listen(3000, function(){ 44 console.log(\'listening on *:3000\'); 45 });
客户端示例:
1 <!doctype html> 2 <html> 3 <head> 4 <title>Socket.IO chat</title> 5 <style> 6 * { margin: 0; padding: 0; box-sizing: border-box; } 7 body { font: 13px Helvetica, Arial; } 8 form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; } 9 form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; } 10 form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; } 11 #messages { list-style-type: none; margin: 0; padding: 0; } 12 #messages li { padding: 5px 10px; } 13 #messages li:nth-child(odd) { background: #eee; } 14 </style> 15 </head> 16 <body> 17 <ul id="messages"></ul> 18 <form action=""> 19 <input id="m" autocomplete="off" /><button>Send</button> 20 </form> 21 <script src="http://code.jquery.com/jquery-1.11.1.js"></script> 22 <script src="/socket.io/socket.io.js"></script> 23 <script> 24 var socket = io(); 25 $(\'form\').submit(function(){ 26 socket.emit(\'chat message\', $(\'#m\').val()); 27 $(\'#m\').val(\'\'); 28 return false; 29 }); 30 socket.on(\'chat message\', function(msg){ 31 $(\'#messages\').append($(\'<li>\').text(msg)); 32 }); 33 </script> 34 35 36 </body> 37 </html>
以上是关于socket.io安装部署的主要内容,如果未能解决你的问题,请参考以下文章
Socket.io 在 localhost 上工作,但在部署 heroku 后无法工作?
socket io连接在localhost中正常工作,但在heroku服务器上部署时却没有