由于您没有完整的代码,我无法清楚地了解您的设置。 LiteCable 的默认broadcast_adapter 是memory,因此如果您要从控制台广播,控制台外的进程将不会收到此类流。如果你使用anycable adapter,我相信它在redis中排队广播,那么只要你有正确的连接,你应该能够从你的控制台广播。
这里是一个简单的 WS 客户端和一个使用没有 Rails 的 LiteCable 实现的服务器
# ~/app/server.rb
# A simple WS server that evaluates math expression literally using ruby eval
# Run this server with ruby server.rb
require "rack"
require "rack/handler/puma"
require "lite_cable"
require "lite_cable/server"
class CalculatorConnection < LiteCable::Connection::Base
identified_by :token
def connect
self.token = request.params["token"]
$stdout.puts "Session #{token} is connected to the server"
end
def disconnect
$stdout.puts "Session #{token} disconnected from the server"
end
end
class CalculatorChannel < LiteCable::Channel::Base
identifier :calculator
def subscribed
stream_from "calculator"
end
def evaluate(payload)
$stdout.puts "Data received from the client"
LiteCable.broadcast "calculator", result: eval(payload['expression'])
end
end
app = Rack::Builder.new
app.map "/cable" do
use LiteCable::Server::Middleware, connection_class: CalculatorConnection
run(proc { |_| [200, {"Content-Type" => "text/plain"}, ["OK"]] })
end
Rack::Handler::Puma.run app
// ~/app/client.js
// A client that talks to the WS server.
// To run, Open chrome console and paste this code
let socket = null;
(function init() {
socket = new WebSocket("ws://0.0.0.0:9292/cable?token=abc123");
socket.onopen = function (e) {
console.info("[connected] : Connection established to the server");
};
socket.onmessage = function (e) {
console.info("[message] : Message from the server", e.data);
};
socket.onerror = function (e) {
console.error("[error] : Error establishing connection", e.message);
};
})();
// subscribe to the calculator channel
socket.send(
JSON.stringify({
command: "subscribe",
identifier: JSON.stringify({
channel: "calculator",
}),
})
);
// call the evaluate method on the Calculator channel
socket.send(
JSON.stringify({
command: "message",
identifier: JSON.stringify({
channel: "calculator",
}),
data: JSON.stringify({
expression: "150 * 4 - 3 / (2 + 2)",
action: "evaluate",
}),
})
);
这里没有什么特别之处,只是一个使用 Puma 的简单机架应用程序,它增加了对机架套接字劫持的支持。这应该会引导您朝着正确的方向前进。确保您的服务器和 chrome 控制台都保持打开状态以查看输出。尝试向服务器发送其他消息以查看输出。
如果您正在考虑在 ruby 中而不是使用 LiteCable 的 js 中实现 WebSocket 客户端,请在 LiteCable 存储库中查看check the client socket class