Ruby on Rails 5中如何给WebSocket同时发送请求头与数据?
Got it! Let's tackle how to set custom request headers for a WebSocket client in Rails 5—you've got a couple solid options here, even beyond the websocket-client-simple gem you mentioned.
You might not have noticed, but websocket-client-simple relies on the websocket-driver gem under the hood, which does support passing custom headers during the handshake. You can specify them directly when initializing the connection:
require 'websocket-client-simple' # Initialize the WebSocket connection with custom headers ws = WebSocket::Client::Simple.connect( 'ws://your-websocket-endpoint.com', headers: { 'X-App-Identifier' => 'rails-client-123', 'Authorization' => 'Bearer your-auth-token-here' } ) # Set up event handlers as usual ws.on :open do puts "Connection established!" ws.send "Hello from Rails WebSocket client!" end ws.on :message do |msg| puts "Received: #{msg.data}" end ws.on :close do |e| puts "Connection closed: #{e}" end # Keep the client running loop { sleep 1 }
The headers hash you pass will be included in the initial HTTP handshake request that upgrades to WebSocket, so your server should pick them up just like any other request headers.
If you want a more robust, explicitly supported way to set headers, the faye-websocket gem is a great alternative. It's widely used and has first-class support for custom headers.
First, add it to your Gemfile:
gem 'faye-websocket' gem 'eventmachine' # Required for handling the event loop
Run bundle install to install the dependencies.
Then use it in your client code:
require 'faye/websocket' require 'eventmachine' # Start the EventMachine loop (required for Faye's async handling) EM.run do ws = Faye::WebSocket::Client.new( 'ws://your-websocket-endpoint.com', nil, # Leave as nil if you don't need WebSocket subprotocols headers: { 'X-Custom-Header' => 'my-custom-value', 'User-Agent' => 'Rails-Faye-Client/1.0' } ) ws.on :open do |event| puts "WebSocket connection opened successfully" ws.send "Greetings from Faye client!" end ws.on :message do |event| puts "Received message: #{event.data}" end ws.on :close do |event| puts "Connection closed: #{event.code} - #{event.reason}" EM.stop # Terminate the event loop when done end ws.on :error do |event| puts "Error encountered: #{event.message}" end end
This gem gives you more control over the connection lifecycle and makes header configuration explicit, which is helpful for debugging or more complex client setups.
In a Rails context, you can wrap this code in a Rake task, a background job, or a standalone script—just make sure to handle the EventMachine loop properly (it's designed for async operations, so it won't block your Rails app if used correctly).
内容的提问来源于stack exchange,提问作者satish

