百科.dev
全部条目AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
G

geckos.io

> 编程语言
开源

使用 WebRTC 和 Node.js 通过 UDP 进行实时客户端/服务器通信 http://geckos.io

1.5K stars0 点赞0 次浏览
访问官网GitHub

工具介绍

使用 WebRTC 和 Node.js 通过 UDP 进行实时客户端/服务器通信 http://geckos.io


:mega: Version 3 Available!

Version 3 of geckos.io is based on [email protected] and only supports ESM and Node.js >=16. There are no other breaking changes.

Version 2

Version 2 has huge performance improvements. I switched from wrtc to node-datachannel, which is much lighter and faster compared to wrtc.

Geckos.io is now shipped as ECMAScript modules and will only support Node.js ^14.15 and >=16.

Install it

 npm i @geckos.io/client @geckos.io/server

Want to know more? Join the discussions!


Who should NOT use this library?

  • People who have never build a multiplayer game, should probably use a library like socket.io instead, since there are way more examples/tutorial available.
    Socket.io and geckos.io use a similar API. The switch from socket.io to geckos.io should be easy.

  • People who have no experiences setting up their own servers with UDP port forwarding, should probably look for a simple solution like websocket, although it is slower.

Menu

  • What is it made for?
  • Getting Started
  • Changelog
  • Documentation
    • Usage
    • Troubleshooting
    • Cheatsheet
    • Raw Messages
    • Reliable Messages
    • Server
    • Deployment
    • ICE Servers
    • TypeScript
    • Docker
    • Examples
  • And some more things at the end of this file.

What is it made for?

It's designed specifically for your HTML5 real-time multiplayer games by lowering the average latency and preventing huge latency spikes. It allows you to communicate with your node.js server via UDP, which is much faster than TCP (used by WebSocket). Take a look at the comparison video between UDP and TCP. https://youtu.be/ZEEBsq3eQmg

Getting Started

First things first, install it via npm:

npm install @geckos.io/client @geckos.io/server

And now, read the Documentation.

Btw, make sure you also check out enable3d.io.


Changelog

New in version 2.3.0

Multiplexing

When true (default), the first available port in the port range will be used for all connections, instead of assigning a new port for each connection.
Thanks to @arthuro555 and @paullouisageneau.

// server.js
const io = geckos({
  multiplex: true // default
})

New in version 1.7.1

You can now pass a more complex url to the client when you set port to null. This is useful if, for example, you use the geckos.io server behind a proxy.

…

New in version 1.7.0

Custom Port Range

Allows you to set a custom port range for the WebRTC connection.

// server.js
const io = geckos({
  portRange: {
    min: 10000,
    max: 20000
  }
})

New in version 1.6.0

Connections Manager

You now have access to the connections manager.

// get any channel by its ID via the connectionsManager
const connection = io.connectionsManager.getConnection(channel.id)
if (connection) {
  // here, you could emit a message ...
  connection.channel.emit('chat message', 'You have been kicked for cheating!')
  // ... or close the channel
  connection.channel.close()
}

Raw messages from the io scope

Finally you can send rawMessages from the io scope.

server

// emit a raw message to all channels
io.raw.emit(rawMessage)

// emit a raw message to a specific room
io.raw.room('roomId').emit(rawMessage)

Authorization and Authentication

The client is now able to send a authorization header with the connection request. If the authorization fails, the server will respond with 401 (unauthorized).

Whatever you add to the option authorization (must be a string) will be sent as a Authorization request header. You could, for example, send Basic base64-encoded credentials, Bearer tokens or a simple string, as in the example below.

Read more about HTTP authentication here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization.

client

const username = 'Yannick'
const password = '12E45'
const auth = `${username} ${password}` // 'Yannick 12E45'
const channel = geckos({ authorization: auth })

channel.onConnect(error => {
  if (error) {
    console.error('Status: ', error.status)
    console.error('StatusText: ', error.statusText)
  }
  console.log(channel.userData) // { username: 'Yannick', level: 13, points: 8987 }
})

server

…

New in version 1.5.0

New autoManageBuffering option

By default the RTCDataChannel queues data if it can't be send directly. This is very bad for multiplayer games, since we do not want to render old state. In version 1.5.0, the option autoManageBuffering was added. It is set to true by default. If autoManageBuffering is on, Geckos.io will prefer to drop messages instead of adding them to the send queue. (Messages with the option { reliable: true }, will still be added to the queue)

The problem with the queue while gaming?

If you send 30Kbytes @60fps and the client only has a 10Mbit connection, he can never receive all messages. So it is necessary to drop some of them, which will be done automatically with autoManageBuffering.
Another good solution to this problem would be to decrease the send rate for that specific client. Use the new channel.onDrop(drop => {}) method to track dropped messages. If, for example, you notice that 20% of the messages for a specific client are dropped, decrease the send rate.


Usage

client.js

import geckos from '@geckos.io/client'

// or add a minified version to your index.html file
// https://github.com/geckosio/geckos.io/tree/master/bundles

const channel = geckos({ port: 3000 }) // default port is 9208

channel.onConnect(error => {
  if (error) {
    console.error(error.message)
    return
  }

  channel.on('chat message', data => {
    console.log(`You got the message ${data}`)
  })

  channel.emit('chat message', 'a short message sent to the server')
})

server.js

import geckos from '@geckos.io/server'

const io = geckos()

io.listen(3000) // default port is 9208

io.onConnection(channel => {
  channel.onDisconnect(() => {
    console.log(`${channel.id} got disconnected`)
  })

  channel.on('chat message', data => {
    console.log(`got ${data} from "chat message"`)
    // emit the "chat message" data to all channels in the same room
    io.room(channel.roomId).emit('chat message', data)
  })
})

Troubleshooting

  • Geckos does not run on http://localhost:PORT/? Try http://127.0.0.1:PORT/ instead.
  • If server listener is listening but never establishes a connection, that might be due to your machine not exposing OPENSSL environment variables (see https://github.com/geckosio/geckos.io/pull/260). To add them try the following:
Exposing OPENSSL environment variables
  1. Find the path to OpenSSL:
brew --prefix openssl
  1. Set the environment variables. You can set the environment variables in your shell by adding the following lines to your shell profile file (usually ~/.bash_profile, ~/.bashrc, or ~/.zshrc for Zsh):
export OPENSSL_ROOT_DIR=/usr/local/opt/[email protected]
export OPENSSL_CRYPTO_LIBRARY=/usr/local/opt/[email protected]/lib
export OPENSSL_INCLUDE_DIR=/usr/local/opt/[email protected]/include

Replace /usr/local/opt/[email protected] with the path you got from the second step. Then, save the file and restart your terminal for the changes to take effect.

  1. Check that the environment variables are set (maybe you'll need to restart your terminal):
echo $OPENSSL_ROOT_DIR
echo $OPENSSL_CRYPTO_LIBRARY
echo $OPENSSL_INCLUDE_DIR
  1. Done ✅

Cheatsheet

Here a list of available methods.

Client

…

Server

…

Note: The following event names are reserved:

  • sendOverDataChannel
  • receiveFromDataChannel
  • disconnected
  • disconnect
  • connection
  • connect
  • error
  • dataChannelIsOpen
  • sendToRoom
  • sendToAll
  • forwardMessage
  • broadcastMessage
  • rawMessage
  • dropped

Raw Messages

You can send and receive USVString, ArrayBuffer and ArrayBufferView using rawMessages.

client

// emit a raw message to the server
channel.raw.emit(rawMessage)

server

// emit a raw message to all channels
io.raw.emit(rawMessage)

// emit a raw message to a specific room
io.raw.room('roomId').emit(rawMessage)

// emit a raw message to the channel
channel.raw.emit(rawMessage)

// emit a raw message to all users in the same room
channel.raw.room.emit(rawMessage)

// broadcast a raw message
channel.raw.broadcast.emit(rawMessage)

// listen for a raw message
channel.onRaw(rawMessage => {})

Reliable Messages

All emit function can send reliable message if needed. This is NOT meant to be used as the default. Just use it to send important messages back and forth.

It works by simply transferring multiple messages after each other. The receiver will simply reject a message if it has already been processed.

channel.emit(
  'end of game',
  {
    points: 147,
    time: 650,
    achievements: ['crucial_hit', 'golden_trophy']
  },
  {
    // Set the reliable option
    // Default: false
    reliable: true,
    // The interval between each message in ms (optional)
    // Default: 150
    interval: 150,
    // How many times the message should be sent (optional)
    // Default: 10
    runs: 10
  }
)

Servers

Standalone

import geckos from '@geckos.io/server'
const io = geckos()

io.onConnection( channel => { ... })
io.listen(3000) // default port is 9208

Node.js HTTP Server

import geckos from '@geckos.io/server'
import http from 'http'

const server = http.createServer()
const io = geckos()

io.addServer(server)
io.onConnection( channel => { ... })
// make sure the client uses the same port
// @geckos.io/client uses the port 9208 by default
server.listen(3000)

Express

import geckos from '@geckos.io/server'
import http from 'http'
import express from 'express'

const app = express()
const server = http.createServer(app)
const io = geckos()

io.addServer(server)
io.onConnection( channel => { ... })
// make sure the client uses the same port
// @geckos.io/client uses the port 9208 by default
server.listen(3000)

Deployment

You have to make sure you deploy it to a server which forwards all traffic on ports 9208/tcp (or another port you define) and 1025-65535/udp to your application.

Port 9208/tcp (or another port you define) is used for the peer signaling. The peer connection itself will be on a random port between 1025-65535/udp.

ICE Servers

Geckos.io provides a default list of ICE servers for testing. In production, you should probably use your own STUN and TURN servers.

import geckos, { iceServers } from '@geckos.io/server'

// use an empty array if you are developing locally
// use the default iceServers if you are testing it on your server
const io = geckos({ iceServers: null, TESTING_LOCALLY ? [] : iceServers })

Watch a useful video about ICE Servers on YouTube.

TypeScript

Geckos.io is written in TypeScript. If you import geckos.io with the import statement, the types will be imported as well.

// client.js
import geckos, { Data } from '@geckos.io/client'

const channel = geckos({ url: 'YOUR_SERVER_URL' })

channel.onConnect(() => {
  channel.on('chat message', (data: Data) => {
    // ...
  })
})

// server.js
i

GitHub Issues· 4 开放

在 GitHub 查看全部
  • #245

    Datachannel connection failing when server running in docker

    更新于 2024年8月26日
  • #203

    .on() doesnt register multiple listeners

    更新于 2024年8月4日
  • #269

    Separate (underlying) datachannels for unreliable and reliable messages

    enhancementhelp wanted更新于 2024年1月28日
  • #280

    Instantiating a geckos client within a web worker throws a ReferenceError

    更新于 2024年1月28日

核心特点

  • •People who have never build a multiplayer game, should probably use a library like socket&#46;io instead, since there are way more examples/tutorial available.
  • •People who have no experiences setting up their own servers with UDP port forwarding, should probably look for a simple solution like websocket, although it is slower.
  • •What is it made for?
  • •Getting Started
  • •Changelog
  • •Documentation
  • •Troubleshooting
  • •Cheatsheet
  • •Raw Messages
  • •Reliable Messages

> 标签

TypeScriptnodejssctpupdwebrtc

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言