博客
关于我
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/

    你可能感兴趣的文章
    Struts2中使用Session的两种方法
    查看>>
    order by rand()
    查看>>
    Orderer节点启动报错解决方案:Not bootstrapping because of 3 existing channels
    查看>>
    org.apache.axis2.AxisFault: org.apache.axis2.databinding.ADBException: Unexpected subelement profile
    查看>>
    org.apache.commons.beanutils.BasicDynaBean cannot be cast to ...
    查看>>
    org.apache.dubbo.common.serialize.SerializationException: com.alibaba.fastjson2.JSONException: not s
    查看>>
    sqlserver学习笔记(三)—— 为数据库添加新的用户
    查看>>
    org.apache.ibatis.exceptions.PersistenceException:
    查看>>
    org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
    查看>>
    org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
    查看>>
    org.apache.poi.hssf.util.Region
    查看>>
    org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
    查看>>
    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.boot:spring boot maven plugin丢失---SpringCloud Alibaba_若依微服务框架改造_--工作笔记012
    查看>>
    SQL-CLR 类型映射 (LINQ to SQL)
    查看>>
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    查看>>
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    查看>>
    org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded
    查看>>