使用WebSocket
客户端:微信小程序
服务器:eggjs+egg-socket.io

弄清楚几个概念。

namespace

// client
import io from 'weapp.socket.io';
// 请求服务器的 'chat' namespace
const server = io('ws://localhost:7001/chat', {
  transports: ['websocket'],
});

// server
// 监听 'chat' namespace下的 one-event-name 事件
app.io.of('chat').route('one-event-name', xxx);

path

这个相当于http的请求路径。

// client
const server = io('ws://localhost:7001/chat', {
  path: '/socket', // default: socket.io
  transports: ['websocket'],
});

// server based on eggjs
config.io = {
    init: {
      path: '/socket',
    },
};

// server based on socket.io directly
const Server = require('socket.io');
const io = Server({
    path: '/socket',
    serveClient: false
  });

在服务端需要根据这个path做反向代理,比如:

location /socket {
  proxy_pass socket_server_address; // 支持socket协议的服务
}

使用的时候,约定好namespace,一般应用用一个namespace就可以。多个namespace可以使用同一个socket连接,也可以使用多个:

// @see https://github.com/socketio/socket.io-client/blob/master/docs/API.md
// By default, a single connection is used when connecting to different namespaces (to minimize resources):

const socket = io();
const adminSocket = io('/admin');
// a single connection will be established

// That behaviour can be disabled with the forceNew option:
const socket = io();
const adminSocket = io('/admin', { forceNew: true });
// will create two distinct connections

// Note: reusing the same namespace will also create two connections
const socket = io();
const socket2 = io();
// will also create two distinct connections
No Comments

Send Comment Edit Comment


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
Previous
Next