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

來源:互聯網
上載者:User

標籤:query   pre   即時聊天   creates   它的   box   add   socket.io   inpu   

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');});
重點:
  1. 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);
  2. 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>

index.html和官網的一樣,不做任何改動

最後執行node index.js,開啟瀏覽器,輸入http://localhost:3000就可以實現最簡單的聊天了

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

聯繫我們

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