如何使用koa实现socket.io官网的例子
socket.io官网中使用express实现了一个最简单的IM即时聊天,今天我们使用koa来实现一下
### 框架准备
- 确保你本地已经安装好了nodejs和npm,使用koa要求node版本>7.6
- 在你需要的位置新建一个文件夹(官网的简单命名为chat-example)
- 进入项目目录,创建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>
index.html和官网的一样,不做任何改动
最后执行node index.js,打开浏览器,输入http://localhost:3000就可以实现最简单的聊天了
如何使用koa实现socket.io官网的例子的更多相关文章
- 详解如何使用koa实现socket.io官网的例子
socket.io官网中使用express实现了一个最简单的IM即时聊天,今天我们使用koa来实现一下利用 socket.io 实现消息实时推送 框架准备 1.确保你本地已经安装好了nodejs和np ...
- NodeJS+Express+Socket.io的一个简单例子
关键字:NodeJS,Express,Socket.io. OS:Windows 8.1 with update pro. 1.安装NodeJS:http://nodejs.org/. 2.初始化一个 ...
- xlwt 官网的例子
from time import * from xlwt.Workbook import * from xlwt.Style import * style = XFStyle() wb = Workb ...
- 关于socket.io的使用
这段时间学习了socket.io,用它写了小项目,在此总结下它的基本使用方式和一些要点. socket.io是基于Node.js和WebSocket协议的实时通信开源框架,它包括客户端的JavaScr ...
- socket.io 入门篇(一)
本文原文地址:https://www.limitcode.com/detail/591b114bb1d4fe074099d9c9.html 前言 本篇介绍使用node.js模块组件socket.io实 ...
- 基于 nodejs 的 webSockt (socket.io)
基于 nodejs 的 webSockt (socket.io) 理解 本文的业务基础是在基于 nodejs 的 socket.io 的直播间聊天室(IM)应用来的. 项目中具体的 框架如下 expr ...
- Socket.IO学习之基础入门
原文:http://blog.csdn.net/weichuang_1/article/details/48831957 这里贴出Socket.IO官网 一.Socket.IO的介绍 Socket.I ...
- socket.io websocket
不能不知道的事: 在Http协议中,客户端向服务器端发送请求,服务器端收到请求再进行回应,整个过程中,服务器端是被动方,客户端是主动方: websoket是H5的一种基于TCP的新通信协议,它与Htt ...
- 利用socket.io+nodejs打造简单聊天室
代码地址如下:http://www.demodashi.com/demo/11579.html 界面展示: 首先展示demo的结果界面,只是简单消息的发送和接收,包括发送文字和发送图片. ws说明: ...
随机推荐
- QQ的全国地址编码
D:\Program Files (x86)\Tencent\QQ\I18N\2052\LocList.xml
- 【JavaEE】WebService到底是什么?
一.序言 大家或多或少都听过WebService(Web服务),有一段时间很多计算机期刊.书籍和网站都大肆的提及和宣传WebService技术,其中不乏很多吹嘘和做广告的成分.但是不得不承认的是Web ...
- 在 Angularjs 中 ui-sref 和 $state.go 如何传递单个多个参数和将对象作为参数
一: 如何传递单个参数 首先,要在目标页面定义接受的参数: 传参, 接收参数, 在目标页面的controller里注入$stateParams,然后 "$stateParams.参数名&qu ...
- JAVA基础系列(一) 概述与相关概念
万事开头难,来这个平台上已经有一段时间了,看到了很多高质量的文章,也很喜欢这种简约的风格.一直也想把自己的零散的知识体系组织起来,但苦于自己拙劣的文笔和不成流派的风格让大家笑话,直到现在才开始.可是从 ...
- 学习笔记:MDN的JavaScript
JavaScript 第一步 什么是JavaScript? 每次当你浏览网页时不只是显示静态信息—— 显示即时更新的内容, 或者交互式的地图,或 2D/3D 图形动画,又或者自动播放视频等,你可以确信 ...
- 属性,选择器和css
一.属性 属性:表示事物的一些特征 属性分为标签属性和样式属性 标签属性:<img src="1.jpg" width="200px" heifht=&q ...
- windows10下git报错warning: LF will be replaced by CRLF in readme.txt. The file will have its original line endings in your working directory.
window10下使用git时 报错如下: $ git add readme.txtwarning: LF will be replaced by CRLF in readme.txt.The fil ...
- 解决mysql连接输入密码提示Warning: Using a password on the command line interface can be insecure
有时候客户端连接mysql需要指定密码时(如用zabbix监控mysql)5.6后数据库会给出个警告信息 mysql -uroot -pxxxx Warning: Using a password o ...
- LeetCode Count and Say 数数字
class Solution { public: string countAndSay(int n) { ) "; "; int i,t,count; char c='*'; ;i ...
- android RadioGroup设置某一个被选中
见码滚 mPriorityRadioGroup.clearCheck(); mStatusRadioGroup.clearCheck(); RadioButton r1 = (RadioButton) ...