DEV Community

sebyx07
sebyx07

Posted on

1

Ruby(Opal) + Express.js + Socket.io. Real time chat Server implementation

Opal implementation of a simple server with Express and Socket.io

Link to the implementation: https://github.com/sebyx07/opal-express-socketio

Demo https://opal-realtime-socket-express.herokuapp.com/

Run

Installation

git clone https://github.com/sebyx07/opal-express-socketio.git opal-server
cd opal-server
bundle install && yarn install # install deps

Update index.html

var socket = io.connect('https://opal-realtime-socket-express.herokuapp.com', {transports:['websocket']});
// with
var socket = io.connect('http://localhost:8000', {transports:['websocket']});

Usage

Replace

rake it's the default rake task that starts the server

go to http://localhost:8000

Server.new(8000) do |s, io|
  s # you can access express methods: with get, post, use, etc. Most is supported
    # callbacks, you replace them with do; end blocks

  io # you can use socket-io methods: on, emit etc. Most is supported
     #  socket must be wrapped using Native()
end

Example server usage

Server.new(8000) do |s, io|
  # express part
  s.use(Logger) # use middlewares
  s.start! # start the server

  s.get("/") do |_, res| # handle get to root request
    res.sendFile(s.view("index.html")) # send the index html file
  end

  s.get("/:name") do |req, res| # handle dynamic requests
    res.send(req.params.name)
  end

  # socket io part
  io.on 'connection' do |socket| # initialize socket io connection
    socket = Native(socket) # if you have problems with apply for a object, just Native() it

    socket.on('chat message') do |msg| # listen for messages
      io.emit('chat message', msg) # send it back, to all clients
    end

    socket.on('disconnect') do # handle disconnect
      p "disconnect"
    end
  end
end

Hopefully, someone will pick this up and build a framework around it. Like with Hyperstack

Billboard image

The fastest way to detect downtimes

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitoring.

Get started now

Top comments (0)

Billboard image

Use Playwright to test. Use Playwright to monitor.

Join Vercel, CrowdStrike, and thousands of other teams that run end-to-end monitors on Checkly's programmable monitoring platform.

Get started now!

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay