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官网的例子的更多相关文章

  1. 详解如何使用koa实现socket.io官网的例子

    socket.io官网中使用express实现了一个最简单的IM即时聊天,今天我们使用koa来实现一下利用 socket.io 实现消息实时推送 框架准备 1.确保你本地已经安装好了nodejs和np ...

  2. NodeJS+Express+Socket.io的一个简单例子

    关键字:NodeJS,Express,Socket.io. OS:Windows 8.1 with update pro. 1.安装NodeJS:http://nodejs.org/. 2.初始化一个 ...

  3. xlwt 官网的例子

    from time import * from xlwt.Workbook import * from xlwt.Style import * style = XFStyle() wb = Workb ...

  4. 关于socket.io的使用

    这段时间学习了socket.io,用它写了小项目,在此总结下它的基本使用方式和一些要点. socket.io是基于Node.js和WebSocket协议的实时通信开源框架,它包括客户端的JavaScr ...

  5. socket.io 入门篇(一)

    本文原文地址:https://www.limitcode.com/detail/591b114bb1d4fe074099d9c9.html 前言 本篇介绍使用node.js模块组件socket.io实 ...

  6. 基于 nodejs 的 webSockt (socket.io)

    基于 nodejs 的 webSockt (socket.io) 理解 本文的业务基础是在基于 nodejs 的 socket.io 的直播间聊天室(IM)应用来的. 项目中具体的 框架如下 expr ...

  7. Socket.IO学习之基础入门

    原文:http://blog.csdn.net/weichuang_1/article/details/48831957 这里贴出Socket.IO官网 一.Socket.IO的介绍 Socket.I ...

  8. socket.io websocket

    不能不知道的事: 在Http协议中,客户端向服务器端发送请求,服务器端收到请求再进行回应,整个过程中,服务器端是被动方,客户端是主动方: websoket是H5的一种基于TCP的新通信协议,它与Htt ...

  9. 利用socket.io+nodejs打造简单聊天室

    代码地址如下:http://www.demodashi.com/demo/11579.html 界面展示: 首先展示demo的结果界面,只是简单消息的发送和接收,包括发送文字和发送图片. ws说明: ...

随机推荐

  1. Microsoft JDBC Driver 使用 getParameterMetaData 会报错?

    不知道为何使用 Microsoft JDBC Driver for SQL Server 驱动时,sql语句不带参数没有问题,但是如果带参数且使用 getParameterMetaData 就会提示某 ...

  2. 【ACM】取石子 - 博弈论

    取石子(一) 时间限制:3000 ms  |  内存限制:65535 KB 难度:2   描述 一天,TT在寝室闲着无聊,和同寝的人玩起了取石子游戏,而由于条件有限,他/她们是用旺仔小馒头当作石子.游 ...

  3. TortoiseSVN 控制图标未显示或显示异常解决方法

  4. Oracle同义词。。。

    同义词 --私有同义词--私有同义词权限grant create synonym to scott;--创建私有同义词create synonym dp for scott.dept;--将查询dep ...

  5. Cmd命令 关机

    at 22:00 Shutdown -s 到了22点电脑就会出现"系统关机"对话框,默认有30秒钟的倒计时并提示你保存工作 Shutdown.exe -s -t 3600 这里表示 ...

  6. 安装flask-mysqldb的时候,提示 mysql_config not found 的解决方法

    解决办法: sudo apt-get install libmysqlclient-dev sudo updatedb locate mysql_config 然后进入mysql_config的路径( ...

  7. 并发编程:synchronized 锁升级过程的验证

        关于synchronized关键字以及偏向锁.轻量级锁.重量级锁的介绍广大网友已经给出了太多文章和例子,这里就不再重复了,也可点击链接来回顾一下.在这里来实战操作一把,验证JVM是怎么一步一步 ...

  8. springboot 学习笔记(九)

    springboot整合activemq,实现broker集群部署(cluster) 1.为实现jms高并发操作,需要对activemq进行集群部署,broker cluster就是activemq自 ...

  9. jquery UI_tabs

    1.tab使用 <!doctype html> <html lang="en"> <head> <meta charset="u ...

  10. IP地址与数字地址相互转换

    /// <summary> /// IP地址转换成数字 /// </summary> /// <param name="addr">IP地址&l ...