博客
关于我
socket.io
阅读量:527 次
发布时间:2019-03-08

本文共 940 字,大约阅读时间需要 3 分钟。

const Koa = require('koa');const Router = require('koa-router');const static = require('koa-static');const app = new Koa();const router = new Router();

// 配置静态文件目录app.use(static(__dirname + '/static'));

// 定义路由router.get('/text', ctx => {ctx.body = '欢迎访问我的 node.js 服务器!';});

// WebSocket配置const server = require('http').createServer(app.callback());const io = require('socket.io')(server);

io.on('connection', socket => {console.log('已连接');// 定期发送数据const userdata = {name: '测试用户',age: 18};// setInterval(() => {// io.emit('getData', userdata);// }, 1000);

socket.on('addData', data => {    console.log('收到数据:', data);    io.emit('getData', data);});

});

server.listen(8989, () => {console.log('服务器已启动,监听地址为 http://localhost:8989');});

// 功能介绍:// 1. 使用 Koa框架搭建 HTTP 服务器// 2. 配置静态文件访问目录// 3. 配置 WebSocket 服务// 4. 实现动态数据接收和发送

注:

  • 本代码基于 ES6 式语法,建议启用相应的语法支持
  • WebSocket 实现一个简单的数据发送机制
  • 可根据实际需求添加更多 WebSocket 消息处理逻辑
  • 服务器监听地址为 http://localhost:8989 模块路径
  • 转载地址:http://gawiz.baihongyu.com/

    你可能感兴趣的文章
    Oracle零碎要点---多表联合查询,收集数据库基本资料
    查看>>
    Oracle静默安装
    查看>>
    Oracle面试题:Oracle中truncate和delete的区别
    查看>>
    ThreadLocal线程内部存储类
    查看>>
    thinkphp 常用SQL执行语句总结
    查看>>
    Oracle:ORA-00911: 无效字符
    查看>>
    Text-to-Image with Diffusion models的巅峰之作:深入解读 DALL·E 2
    查看>>
    TCP基本入门-简单认识一下什么是TCP
    查看>>
    Orcale表被锁
    查看>>
    org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
    查看>>
    org.apache.poi.hssf.util.Region
    查看>>
    org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
    查看>>
    org.hibernate.HibernateException: Unable to get the default Bean Validation factory
    查看>>
    org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
    查看>>
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    查看>>
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    查看>>
    org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded
    查看>>
    org.tinygroup.serviceprocessor-服务处理器
    查看>>
    org/eclipse/jetty/server/Connector : Unsupported major.minor version 52.0
    查看>>
    org/hibernate/validator/internal/engine
    查看>>