国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

詳解如何使用koa實現socket.io官網的例子

2024-05-06 15:28:14
字體:
來源:轉載
供稿:網友

socket.io官網中使用express實現了一個最簡單的IM即時聊天,今天我們使用koa來實現一下

### 框架準備

1.確保你本地已經安裝好了nodejs和npm,使用koa要求node版本>7.6

2.在你需要的位置新建一個文件夾(官網的簡單命名為chat-example)

3.進入項目目錄,創建package.json文件:

{ "name": "socket-chat-example", "version": "0.0.1", "description": "my first socket.io app", "dependencies": {}}

4.命令行中使用npm安裝,執行以下命令

npm install --save koa koa-router http fs socket.io

### 接下來直接上代碼

項目目錄下直接新建index.js

var Koa = require('koa');var app = new Koa();const Router = require('koa-router');const fs = require('fs');const server = require('http').createServer(app.callback());const io = require('socket.io')(server);// 首頁路由let router = new Router();router.get('/', ctx => {  ctx.response.type = 'html';  ctx.response.body = fs.createReadStream('./index.html');});app.use(router.routes());// socket連接io.on('connection', (socket) => {  socket.on('chat message', (msg) => {    console.log('message: '+msg);    io.emit('chat message', msg);  });  socket.on('disconnect', () => {    console.log('user disconnected');  });});// 監聽端口server.listen(3000, () => {  console.log('listening on *:3000');});

重點:

socket的連接方式是先建立server,它的獲取方式不再是:

var http = require('http').Server(app);var io = require('socket.io')(http);

而變成了:

const server = require('http').createServer(app.callback());const io = require('socket.io')(server);

node8之后,function(){} 可以簡化為 () => {},寫法上更加的簡潔

頁面index.html

<!doctype html><html> <head>  <title>Socket.IO chat</title>  <style>   * { margin: 0; padding: 0; box-sizing: border-box; }   body { font: 13px Helvetica, Arial; }   form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }   form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }   form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }   #messages { list-style-type: none; margin: 0; padding: 0; }   #messages li { padding: 5px 10px; }   #messages li:nth-child(odd) { background: #eee; }  </style> </head> <body>  <ul id="messages"></ul>  <form action="">   <input id="m" autocomplete="off" /><button>Send</button>  </form>  <script src="/socket.io/socket.io.js"></script>  <script src="https://code.jquery.com/jquery-1.11.1.js"></script>   <script>     $(function () {       var socket = io();       $('form').submit(function(){         socket.emit('chat message', $('#m').val());         $('#m').val('');         return false;       });       socket.on('chat message', function(msg){         $('#message').append($('<li>').text(msg));       });     });   </script> </body></html>            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 盐亭县| 阳信县| 无极县| 玉龙| 定远县| 随州市| 武宁县| 山阴县| 保康县| 祁连县| 农安县| 兖州市| 托里县| 堆龙德庆县| 文成县| 定南县| 临城县| 浏阳市| 德清县| 凤冈县| 平湖市| 云龙县| 凌源市| 蓝山县| 清水县| 三亚市| 类乌齐县| 河南省| 邵阳市| 宾川县| 巧家县| 墨竹工卡县| 镇江市| 来凤县| 平潭县| 巴楚县| 吴桥县| 安福县| 灵宝市| 宁阳县| 开化县|