当前位置: 首页 > 软件库 > Web应用开发 > Web框架 >

koa-socket-2

Socket.IO for Koa
授权协议 Readme
开发语言 JavaScript
所属分类 Web应用开发、 Web框架
软件类型 开源软件
地区 不详
投 递 者 郝池暝
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

Koa-socket-2

Sugar for connecting socket.io to a Koa instance

Koa-socket-2 uses socket.io v3. It is recommended that you connect to a koa-socket-2 server with a socket.io v3 client.

Koa-socket-2 is only compatible with Koa v2 style of middleware (where context is passed as a parameter).

Koa-socket-2 requires Node v7.0.0 or higher.

Interested in GoLang?

This project helps you start a SocketIO server using Koa and NodeJS. However, Google's Go language -- or GoLang -- allows you to write code that compiles down to binary. It can be a very good way to take your SocketIO server to the next level by running faster and requiring less overhead than runtime environments like NodeJS.

If you're interested in building a SocketIO server in GoLang, take a look at gosf.io or GOSF on GitHub, the GoLang SocketIO Framework for building SocketIO API servers.

Installation

npm i -S koa-socket-2

HTTP Example

Please make the world a better place and stop using unsecure channels. If youabsolutely must, however, then the following will get you started.

const Koa = require('koa');
const IO = require('koa-socket-2');

const app = new Koa();
const io = new IO();

app.use( ... );

io.attach(app);

io.on('message', (ctx, data) => {
  console.log('client sent data to message endpoint', data);
});

app.listen( process.env.PORT || 3000 );

HTTPS Example

const Koa = require('koa');
const IO = require('koa-socket-2');
const fs = require('fs');

// If you want to access the HTTPS server from a local JS client for
// development, then try this simple plugin:
app.use(async (ctx, next) => {
  ctx.set('Access-Control-Allow-Origin', 'null');
  ctx.set('Access-Control-Allow-Credentials', 'true');
  await next();
});

const app = new Koa();
const io = new IO();

app.use( ... );

// Replace the "..." placeholders below with your own SSL certificate files
io.attach(app, true, {
  key: fs.readFileSync(...),
  cert: fs.readFileSync(...),
  ca: fs.readFileSync(...)
});

console.log('Server: HTTPS/TLS Enabled.');

io.on('message', (ctx, data) => {
  console.log('client sent data to message endpoint', data);
});

app.listen(process.env.PORT || 3000);

Features

  • Attach socket.io to existing koa projects
  • Attach koa-style middleware to socket.io events
  • Supports koa v2 style of passing context along the response chain

Attaching to existing projects

The attach function is used to attach the IO instance to the application, this adds server* and io properties to the koa application and should happen before the app starts listening on a port.

It also re-maps app.listen to app.server.listen, so you could simply do app.listen(). However if you already had an app.server attached, it uses it instead and expects you to do app.server.listen() yourself.

const Koa = require( 'koa' );
const IO = require( 'koa-socket-2' );

const app = new Koa();
const io = new IO();

// Attach the socket to the application
io.attach( app );

// Socket is now available as app.io if you prefer
app.io.on( event, eventHandler );

// The raw socket.io instance is attached as app._io if you need it
app._io.on( 'connection', sock => {
  // ...
});

// *If* you had manually attached an `app.server` yourself, you should do:
app.listen = function() {
  app.server.listen.apply(app.server, arguments);
  return app.server;
}

// app.listen is mapped to app.server.listen, so you can just do:
app.listen( process.env.PORT || 3000 );

Middleware and event handlers

Middleware can be added in much the same way as it can be added to any regular koa instance.

Example with async functions

io.use( async ( ctx, next ) => {
  let start = new Date();
  await next();
  console.log( `response time: ${ new Date() - start }ms` );
})

Example with generator functions

Don't use generator functions. Get with the times, and upgrade to Node >= 7.X.X.

Plain example

Whilst slightly unwieldy, the standalone method also works

io.use( ( ctx, next ) => {
  let start = new Date()
  return next().then( () => {
    console.log( `response time: ${ new Date() - start }ms` )
  })
})

Passed Context

let ctx = {
  event: listener.event,
  data: data,
  socket: Socket,
  acknowledge: cb
}

The context passed to each socket middleware and handler begins the chain with the event that triggered the response, the data sent with that event and the socket instance that is handling the event. There is also a shorthand for firing an acknowledgement back to the client.

As the context is passed to each function in the response chain it is fair game for mutation at any point along that chain, it is up to you to decide whether this is an anti-pattern or not. There was much discussion around this topic for koa v2.

io.use( async ( ctx, next ) => {
  ctx.process = process.pid
  await next()
})

io.use( async ( ctx, next ) => {
  // ctx is passed along so ctx.process is now available
  console.log( ctx.process )
})

io.on( 'event', ( ctx, data ) => {
  // ctx is passed all the way through to the end point
  console.log( ctx.process )
})

Namespaces

Namespaces can be defined simply by instantiating a new instance of koaSocket and passing the namespace id in the constructor. All other functionality works the same, it’ll just be constrained to the single namespace.

const app = new Koa()
const chat = new IO({
  namespace: 'chat'
});

chat.attach( app );

chat.on( 'message', ctx => {
  console.log( ctx.data );
  chat.broadcast( 'response', ... );
});

Namespaces also attach themselves to the app instance, throwing an error if the property name already exists.

const app = new Koa();
const chat = new IO({
  namespace: 'chat'
});

chat.attach( app );

app.chat.use( ... );
app.chat.on( ... );
app.chat.broadcast( ... );

The attachment is configurable if you don’t want to muddy the app object with all your namespaces.

const chat = new IO({
  namespace: 'chat',
  hidden: true
});

chat.use( ... );
chat.on( ... );

Namespaces are fairly ubiquitous so they get a dirty shorthand for creating them, note that if you want to add any additional options you’ll need to use the longhand object parameter to instantiate koaSocket.

const chat = new IO( 'chat' );

IO API

.attach( Koa app )

Attaches to a koa application

io.attach( app );
app.listen( process.env.PORT );

.use( Function callback )

Applies middleware to the stack.

Middleware are executed each time an event is reacted to and before the callback is triggered for an event.

Middleware with generators should use co.wrap.

Middleware functions are called with ctx and next. The context is passed through each middleware and out to the event listener callback. next allows the middleware chain to be traversed. Under the hood koa-compose is used to follow functionality with koa.

io.use( async ( ctx, next ) {
  console.log( 'Upstream' );
  await next();
  console.log( 'Downstream' );
})

.on( String event, Function callback )

Attaches a callback to an event.

The callback is fired after any middleware that are attached to the instance and is called with the ctx object and the data that triggered the event. The data can also be found on the ctx, the only potential difference is that data is the raw data emitted with the event trigger whilst ctx.data could have been mutated within the middleware stack.

io.on( 'message', ( ctx, data ) => {
  console.log( data );
  console.log( ctx.data, data );
});

.off( String event, Function callback )

Removes a callback from an event.

If the event is omitted then it will remove all listeners from the instance.

If the callback is omitted then all callbacks for the supplied event will be removed.

io.off( 'message', onChat );
io.off( 'message' );
io.off();

.broadcast.emit( String event, data )

Sends a message to all connections.

.to( String room ).emit( String event, data )

Sends data to all connections in a room.

io.to( 'some_room' ).emit( 'message', { hello: 'world' } );

.adapter( Object adapter )

const redis = require('socket.io-redis');
io.adapter(redis({ host: 'localhost', port: 6379 }));

Socket Connection API

.rooms

A list of rooms that this connection is associated with.

io.on( 'message', ( ctx, data ) => {
  console.log(ctx.socket.rooms);
});

.join( String room )

Associates the connection with a room.

io.on( 'message', ( ctx, data ) => {
  ctx.socket.join('some_room');
});

.leave( String room )

Disassociates the connection with a room.

io.on( 'message', ( ctx, data ) => {
  ctx.socket.leave( 'some_room' );
});

.broadcast.emit( String event, data )

Sends a message to all active connections except the current connection.

io.on( 'message', ( ctx, data ) => {
  ctx.socket.broadcast.emit( 'message', { hello: 'world' } );
});

.broadcast.to(String room).emit( String event, data )

Sends a message to all active connections in a room except the current connection.

io.on( 'message', ( ctx, data ) => {
  ctx.socket.broadcast.to('some_room').emit( 'message', { hello: 'world' } );
});

.volatile.emit( String event, data )

Sends a message without ensuring delivery.

io.on( 'message', ( ctx, data ) => {
  ctx.socket.volatile.emit( 'message', { hello: 'world' } );
});

.compress(true).emit( String event, data )

Activates per-message compression.

io.on( 'message', ( ctx, data ) => {
  ctx.socket.compress(true).emit( 'message', { hello: 'world' } );
});

Running tests

npm test

Maintainer/Contributor

Original Author

License

MIT

  • 资料:https://www.npmjs.com/package/koa-socket-2            https://socket.io/docs/            http://blog.fens.me/nodejs-socketio-chat/           https://www.npmjs.com/package/socketio-jwt 安装模块 npm i -S

  • 服务端 在Koa2中安装koa-socket模块 cnpm i -S koa-socket 在Koa项目中引入koa-socket const IO = require( 'koa-socket' ) 实例化const io = new IO() const io = new IO() 调用 io.attach( app ) io.attach( app ) 配置服务端 app._i

  • ### koa-socket #### 核心思想socket-io - 轮询ajax 缺点:不停询问服务器,浪费性能 - 服务器不关闭连接,一次响应,一直保持连接 缺点:只有服务器向客户端不断输出 - html5中出来了一个websocket 他是在原来http协议的基础上,去升级当前协议为websocket升级 - 将原本 先有请求才有响应的机制,更改成了,服务端也可以主动发请求给客户端 - H

  • 前言 http的特点是一问一答,而即时通讯是需要双向通信的,这样以前的即时通信只能使用轮询的方式通过周期性的ajax请求获取数据,直到websocket出现,就完美实现了双向通信 一 即时通讯方式简介 段轮询 前台使用setInterval进行定时请求后台,这样无疑非常浪费性能 长轮询和长连接(html5的EventSource) 客服端连接一次,服务端不断开连接,服务端接收到新消息就发送给前台,

  • koa-socket 1.起步 引入 var IO=require('koa-socket'); var io=new IO(); io.attach(app);//将socket和app关联 2.使用 客户端: 首先引入包: <script src="/socket.io/socket.io.js"></script> 服务端和客服端通过on和emit进行交互 emit表示发送,事件名自定义

  • 首先把socket.io和koa2结合在同一个项目中 还是比较简单的 服务端   import Koa from 'koa'; import http from 'http'; import socket from 'socket.io'; const app = new Koa(); //koa中间件 原代码不动 //app.use(...); //如果原来是用app.listen(30

  • Koa集成Socket.io 步骤 类比之前express项目中的使用,有以下几个步骤 安装:$ cnpm i -S koa-socket 引入: const IO = require( 'koa-socket' ) 实例化:const io = new IO() 接入koa: io.attach( app ) 配置服务端 客户端使用 后端演示 var Koa = require('koa'),

  • 去饭店吃饭的时候,桌上都会有一个二维码,每一桌的每一个用户都可以拿出手机独立点餐,而且同一桌的用户点餐都会在同一个购物车里,比如张三与李四一起来吃饭,张三点了青椒炒肉,李四拿出手机点餐的时候,购物车里就会显示张三点的青椒炒肉,而且每一桌的点餐与其他桌的不会相互干扰,付款的时候以桌为单位独立结账。 以上就是基本的业务场景,那么这个功能如何实现呢?下面直接上代码,请大家留意注释。 首先是服务端的实现。

 相关资料
  • Koa

    Koa art-template view render middleware. support all feature of art-template. Install npm install --save art-template npm install --save koa-art-template Example const Koa = require('koa'); const ren

  • koa

    koa是Express的下一代基于Node.js的web框架,目前有1.x和2.0两个版本。 历史 1. Express Express是第一代最流行的web框架,它对Node.js的http进行了封装,用起来如下: var express = require('express'); var app = express(); app.get('/', function (req, res) {

  • Koa

    Koa 是下一代的 Node.js 的 Web 框架。由 Express 团队设计。旨在提供一个更小型、更富有表现力、更可靠的 Web 应用和 API 的开发基础。 Koa可以通过生成器摆脱回调,极大地改进错误处理。Koa核心不绑定任何中间件,但提供了优雅的一组可以快速和愉悦地编写服务器应用的方法。 示例代码: var koa = require('koa');var app = koa();//

  • 一、I/O 模型 阻塞式 I/O 非阻塞式 I/O I/O 复用 信号驱动 I/O 异步 I/O 五大 I/O 模型比较 二、I/O 复用 select poll 比较 epoll 工作模式 应用场景 参考资料 一、I/O 模型 一个输入操作通常包括两个阶段: 等待数据准备好 从内核向进程复制数据 对于一个套接字上的输入操作,第一步通常涉及等待数据从网络中到达。当所等待数据到达时,它被复制到内核中

  • socket是与客户端浏览器交互的基石。socket属于一个确定的命名空间(默认为**/**),并且使用下行客户端沟通讯息。 值得注意的是,这里所指的socket和下行TCP/IP的socket不是一回事儿,这里所指的socket只是一个类名而已。 在每一个命名空间内,你可以定义任意的频道(被叫做房间room的东西),如此socket就可以加入房间或者离开房间。房间的机制使得服务器端可以同时给一组

  • 什么是套接字? Socket是一种Berkeley UNIX机制,用于在不同进程之间创建虚拟双工连接。 随后将其移植到每个已知的OS上,使得能够跨越在不同OS软件上运行的地理位置的系统之间进行通信。 如果不是套接字,系统之间的大多数网络通信永远不会发生。 仔细看看; 网络上的典型计算机系统根据其上运行的各种应用程序接收和发送信息。 此信息被路由到系统,因为为其指定了唯一的IP地址。 在系统上,此信