惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
AWS News Blog
AWS News Blog
V
Vulnerabilities – Threatpost
D
Darknet – Hacking Tools, Hacker News & Cyber Security
量子位
博客园 - 叶小钗
AI
AI
T
Tor Project blog
Forbes - Security
Forbes - Security
W
WeLiveSecurity
博客园_首页
爱范儿
爱范儿
J
Java Code Geeks
B
Blog
G
GRAHAM CLULEY
aimingoo的专栏
aimingoo的专栏
Cloudbric
Cloudbric
C
CXSECURITY Database RSS Feed - CXSecurity.com
TaoSecurity Blog
TaoSecurity Blog
L
LINUX DO - 热门话题
阮一峰的网络日志
阮一峰的网络日志
有赞技术团队
有赞技术团队
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Simon Willison's Weblog
Simon Willison's Weblog
云风的 BLOG
云风的 BLOG
Google DeepMind News
Google DeepMind News
H
Help Net Security
博客园 - 三生石上(FineUI控件)
C
Cisco Blogs
C
Cybersecurity and Infrastructure Security Agency CISA
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
P
Palo Alto Networks Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Recent Commits to openclaw:main
Recent Commits to openclaw:main
博客园 - 司徒正美
The Last Watchdog
The Last Watchdog
Blog — PlanetScale
Blog — PlanetScale
T
The Blog of Author Tim Ferriss
S
Secure Thoughts
Spread Privacy
Spread Privacy
F
Fortinet All Blogs
月光博客
月光博客
大猫的无限游戏
大猫的无限游戏
S
SegmentFault 最新的问题
H
Hackread – Cybersecurity News, Data Breaches, AI and More
A
About on SuperTechFans
Security Latest
Security Latest
Webroot Blog
Webroot Blog
Scott Helme
Scott Helme
Hugging Face - Blog
Hugging Face - Blog

任峻宏的小站

Debugging Memory Leaks in a Next.js Application Troubleshooting: Resolving Devise Issue in an API-only Application How to Customize a Right-Click Menu in React 纪念左耳朵耗子 - 任峻宏的小站 Using SSE to Implement ChatGPT in Rails Refresh Myself - 任峻宏的小站 战痘 - 任峻宏的小站 逆向的能量——生活需要批评者 - 任峻宏的小站 人活着必须要有目标 - 任峻宏的小站 《第一人称单数》读书笔记 - 任峻宏的小站 卸载英雄联盟 - 任峻宏的小站 我的 2021 年总结 - 任峻宏的小站 记我的爷爷 - 任峻宏的小站 Migrate from Webpacker to Vite 从入门到放弃 《人生算法》读书笔记 - 任峻宏的小站 《不拘一格》读书笔记 - 任峻宏的小站 我为什么很少写博客 - 任峻宏的小站 我的2020年总结 - 任峻宏的小站 如何避免冲动消费? - 任峻宏的小站 《不能不去爱的两件事》读书笔记 - 任峻宏的小站 记一次搬家 - 任峻宏的小站 My blog V3.0 has been published! 解决服务器上运行 bundle install 时 killed 的问题 解决生产环境不能发送邮件的问题 - 任峻宏的小站 解决内存泄漏记录 - 任峻宏的小站 勿忘初心 - 任峻宏的小站 关于 RSpec 的一点方法总结 - 任峻宏的小站 使用 AJAX 重载部分页面 - 任峻宏的小站 Nginx 添加 SSL 支持 - 任峻宏的小站 Nginx 中进行重定向配置 - 任峻宏的小站 记我的第二次部署 - 任峻宏的小站 写在“毕业”之际 - 任峻宏的小站 JS 简单实现弹出层效果 - 任峻宏的小站 速递易工作总结及感想 - 任峻宏的小站 在 Aliyun ECS 上用 Nginx + Passenger 部署 Rails 应用时安装 Passenger 的问题 [译] Common Rails Idioms that Kill Database Performance Git 常用操作总结 - 任峻宏的小站 [译] Terminal 功夫——方便开发者的实用技巧 - 任峻宏的小站 实例方法与类方法 - 任峻宏的小站 各种报错解决集合 - 任峻宏的小站
Using ActionCable and React to Create a Simple Chat App
任峻宏 · 2023-06-16 · via 任峻宏的小站

Online example: https://ac.aiichat.cn

Code repository: https://github.com/renny-ren/action-chat

Introduction

In this article, I'm going to explore how to leverage the power of Rails ActionCable and React to build a web chat application. ActionCable provides a straightforward way to incorporate real-time features into Rails applications, while React serves as a powerful and flexible frontend framework. By combining these technologies, we can create an interactive and dynamic chat application. Let's dive into the details of how to implement this solution.

Setting up the Environment

Before we dive into the implementation details, make sure you have the following prerequisites in place:
- Ruby on Rails: Ensure that you have Rails installed on your local machine.
- React: Familiarize yourself with React and have a basic understanding of how React components and states work.

Creating the ActionCable Channel

To begin with, let's create an ActionCable channel for our chat application. In your terminal, run the following command to generate the channel:

rails g channel chat_channel

This command will generate a chat_channel.rb file under the app/channels directory. Open this file and update it as follows:

class ChatChannel < ApplicationCable::Channel
  def subscribed
    stream_from "ChatChannel"
  end

  def unsubscribed
    # Any cleanup needed when the channel is unsubscribed
  end
  
  def receive(data)
    @message = user.messages.create(body: data["body"])
    ActionCable.server.broadcast("ChatChannel", JSON.parse(@message.to_json))
  end
end

stream_from method inside the subscribed specifies the channel you want to subscribe to and receive updates from. It means that whenever there is a new message sent to the ChatChannel, the clients subscribed to this channel will receive the message in real-time.

Creating the ActionCable Consumer

To establish a connection between the client and the server, we need to create an ActionCable consumer in our React application. Add the following code snippet where you want to initiate the connection:

app/javascript/channels/consumer.js

// Create a consumer object
const consumer = ActionCable.createConsumer();

This code initializes an ActionCable consumer object, which acts as the bridge between the client and the server.

Subscribing to the Channel

Now, let's subscribe to the chat channel we created earlier. Use the following code snippet to subscribe to the channel:

// Subscribe to a channel
const subscription = consumer.subscriptions.create("ChatChannel");

Ensure that the channel name passed matches the name of the channel you defined in your Rails application.

Unsubscribing from the Channel

If at any point you want to unsubscribe from the chat channel, you can call the unsubscribe method on the subscription object:

subscription.unsubscribe();

This will effectively terminate the connection and stop receiving updates from the channel.

Disconnecting the Consumer

Finally, when you're done using the consumer object, it's good practice to disconnect it. Use the following code snippet to disconnect the consumer:

consumer.disconnect();

This will release any resources associated with the consumer and prevent unnecessary connections.

Online example: https://ac.aiichat.cn

Code repository: https://github.com/renny-ren/action-chat

Reference

Refer to the following resources for more detailed information and examples:

Integrating ActionCable with React

Simple chatroom with Rails 6 and ActionCable

rails-sse-and-websockets GitHub Repository