如何使用socket.io创建实时搜索?
我使用RethinkDB + Node + Express + Socket.io + Redux + React,我正在监听事件(它是使用rethinkdb创建的更改),它让我在客户端发出10个项目并使用react显示它们。 / p>
现在我想创建实时搜索,它将查询发送到服务器,在DB中搜索结果,返回前10个结果并使用socket.io将它们发送到客户端
// emit events for changes
r.table('stackoverflow_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实现这一点,您是否必须为每个自定义查询动态创建自定义套接字事件侦听器? (对我来说,这听起来很荒谬,应该有一个简单的方法)
答案 0 :(得分:0)
我找到了一个解决方案,这是一个最基本的例子:
// 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)