使用 socket.io 进行实时搜索

Live search using socket.io

如何使用 socket.io 创建实时搜索?

我使用 RethinkDB + Node + Express + Socket.io + Redux + React,我正在监听事件(它是使用 rethinkdb 创建的 changefeed),它在客户端向我发送 10 个项目并显示它们使用反应。

现在我想创建实时搜索,它将查询发送到服务器,在数据库中搜索结果,returns 前 10 个结果并使用 socket.io

将它们发送到客户端
// emit events for changes

r.table('Whosebug_questions')
.changes({ includeInitial: true, squash: true })
.limit(10)
.run(connection)
.then(changefeedSocketEvents(socket, 'topic'))

-

// Socket.io events for changefeed

module.exports = function (socket, entityName) {
  return function (rows) {
    rows.each(function (err, row) {
      if (err) { return console.log(err) } else if (row.new_val && !row.old_val) {
        socket.emit(entityName + ':insert', row.new_val)
      } else if (row.new_val && row.old_val) {
        socket.emit(entityName + ':update', row.new_val)
      } else if (row.old_val && !row.new_val) {
        socket.emit(entityName + ':delete', { id: row.old_val.id })
      }
    })
  }
}

我不知道如何使用 socket.io 实现这一点,您是否必须为每个自定义查询即时创建自定义套接字事件侦听器? (我觉得这听起来很可笑,应该有一个简单的方法)

我找到了一个解决方案,这里是一个最简单的例子:

// server.js

const express = require('express')
const app = express()
const http = require('http')
const server = http.Server(app)
const io = require('socket.io')(server)

app.use(express.static('client'))

io.on('connection', function(client){
    setInterval(() => io.emit('found', 'dfasdfadsfasdfasdf'), 5000)
    console.log('connected with socket: ' + client.id)
client.on('search', function (text) {
    const data = Math.random()
    io.emit('found', data + text)
})
client.on('disconnect', function(){})
})

app.get('/')

server.listen(3000)

-

<!- index.html ->

<!DOCTYPE html>
<html>
<head>
  <script src="/socket.io/socket.io.js"></script>
  <script src="./client.js"></script>
  <title>socket-io-live-search</title>
</head>
<body>
  <div id='search'>
    <input type ='text' />
  </div>
</body>
</html>

-

// client.js

var socket = io()

const loaded = () => {
    const inputEl = document.querySelector('#search input')
    inputEl.oninput = (e) => socket.emit('search', e.target.value)
}

socket.on('found', (data) => console.log('found: ' + data))

document.addEventListener('DOMContentLoaded', loaded, false)