SlideShare una empresa de Scribd logo
1 de 26
Descargar para leer sin conexión
Faye
simple pub/sub messaging
http://faye.jcoglan.com/
• Publish-subscribe messaging system
• Based on the Bayeux protocol
• Servers/clients in Ruby and Javascript
npm install faye




gem install faye
Server
var Faye   = require('faye')
var server = new Faye.NodeAdapter({ mount: '/faye' })

server.listen(8000)
require 'faye'

server = Faye::RackAdapter.new(:mount => '/faye')
server.listen(8000)
Client
var Faye   = require('faye')
var client = new Faye.Client('http://localhost:8000/faye')

// subscribe to a channel
client.subscribe('/messages', function(message) {
   console.log('We got a message: ' + message.text)
})

// publish to a channel
client.publish('/messages', {
   text: 'HAI!'
})
<script type="text/javascript"
        src="http://localhost:8000/faye/client.js"></script>

<script type="text/javascript">
  var client = new Faye.Client('http://localhost:8000/faye')

  client.subscribe('/messages', function(message) {
     alert('We got a message: ' + message.text)
  })
</script>
require 'faye'
require 'eventmachine'

EM.run {
  client = Faye::Client.new('http://localhost:8000/faye')

    # subscribe to a channel
    client.subscribe('/messages') do |message|
      puts message.inspect
    end

    # publish to a channel
    client.publish('/messages', { 'text' => 'HAI!' })
}
Example App
• Simple chat-room application
 • Sinatra
 • Faye
require 'sinatra'

get '/' do
  erb :index
end
var Faye   = require('faye')
var server = new Faye.NodeAdapter({ mount: '/faye' })
server.listen(8000)
<!DOCTYPE html>
<html>
<head>
  <title>Chattr</title>
  <link rel="stylesheet" href="chattr.css" type="text/css" media="screen" />
</head>
<body>
  <h1>Lets Chat...</h1>

  <ul id="chat"></ul>
  <form id="new_message" action="#" method="get" accept-charset="utf-8">
    <input type="text" name="message" id="message" value="" />
    <input type="submit" name="send" id="send" value="Send" />
  </form>

  <script src="jquery.min.js" charset="utf-8"></script>
  <script src="http://localhost:8000/faye/client.js" charset="utf-8"></script>
  <script src="chattr.js" charset="utf-8"></script>
</body>
</html>
var client = new Faye.Client('http://localhost:8000/faye')

// Publish a message...
$('#new_message').bind('submit',function() {
  var now     = new Date()
  var message = {
    content: $('#message').val(),
    timestamp: now.getHours() + ":" + now.getMinutes()
  }

     client.publish('/messages', message)
     $('#message').val('')
     return false
})

// Subscribe to message feed...
client.subscribe('/messages', function(message) {
  var str = ''
  str += '<li>'
  str += ' <span class="created_at">'+ message.timestamp +'</span>'
  str += ' '+ message.content
  str += '</li>'

     $('#chat').append(str)
})
Demo
Server
Events

• handshake
• subscribe
• unsubscribe
• publish
• disconnect
var Faye   = require('faye')
var server = new Faye.NodeAdapter({ mount: '/faye' })
server.listen(8000)

server.bind('handshake', function(client_id) {
   console.log("[handshake] - client: '"+ client_id +"'")
})

server.bind('subscribe', function(client_id, channel) {
   console.log("[subscribe] - client: '"+ client_id +"', channel: '"+ channel +"'")
})

server.bind('unsubscribe', function(client_id, channel) {
   console.log("[unsubscribe] - client: '"+ client_id +"', channel: '"+ channel
+"'")
})

server.bind('publish', function(client_id, channel, data) {
   console.log("[publish] - client: '"+ client_id +"', channel: '"+ channel +"'")
   console.log("[publish] - data:")
   console.log(data)
})

server.bind('disconnect', function(client_id) {
   console.log("[disconnect] - client: '"+ client_id +"'")
})
require 'faye'
require 'logger'

Faye::WebSocket.load_adapter('thin')
faye = Faye::RackAdapter.new(:mount => '/faye', :timeout => 25)

log = Logger.new(STDOUT)
log.level = Logger::INFO

faye.bind(:handshake) do |client_id|
  log.info("[handshake] - client: '#{client_id}'")
end

faye.bind(:subscribe) do |client_id,channel|
  log.info("[subscribe] - client: '#{client_id}', channel: '#{channel}'")
end

faye.bind(:unsubscribe) do |client_id,channel|
  log.info("[unsubscribe] - client: '#{client_id}', channel: '#{channel}'")
end

faye.bind(:publish) do |client_id,channel,data|
  log.info("[publish] - client: '#{client_id}', channel: '#{channel}', data: '#
{data.inspect}'")
end

faye.bind(:disconnect) do |client_id|
  log.info("[disconnect] - client: '#{client_id}'")
end

run faye
Extensions

• Override default behaviour...
 • incoming()
 • outgoing()
Engines


• Change the back-end...
 • faye-redis
var faye       = require('faye')
var faye_redis = require('faye-redis')

var server = new faye.NodeAdapter({
   mount:   '/faye',
   timeout: 25,
   engine:  {
     type:  faye_redis,
     host:  'localhost',
     port:  6379
   }
})
server.listen(8000)
require 'faye'
require 'faye-redis'

server = Faye::RackAdapter.new(
  :mount   => '/faye',
  :timeout => 25,
  :engine => {
    :type => Faye::Redis,
    :host => 'localhost',
    :port => 6379
  }
)
server.listen(8000)
An Introduction to Faye

Más contenido relacionado

Similar a An Introduction to Faye

Server Side Events
Server Side EventsServer Side Events
Server Side Eventsthepilif
 
[WSO2 Integration Summit Madrid 2019] Integration + Ballerina
[WSO2 Integration Summit Madrid 2019] Integration + Ballerina[WSO2 Integration Summit Madrid 2019] Integration + Ballerina
[WSO2 Integration Summit Madrid 2019] Integration + BallerinaWSO2
 
Practical PHP by example Jan Leth-Kjaer
Practical PHP by example   Jan Leth-KjaerPractical PHP by example   Jan Leth-Kjaer
Practical PHP by example Jan Leth-KjaerCOMMON Europe
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of LithiumNate Abele
 
Top 10 F5 iRules to migrate to a modern load balancing platform
Top 10 F5 iRules to migrate to a modern load balancing platformTop 10 F5 iRules to migrate to a modern load balancing platform
Top 10 F5 iRules to migrate to a modern load balancing platformAvi Networks
 
Mashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web AppsMashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web AppsBastian Hofmann
 
Websockets talk at Rubyconf Uruguay 2010
Websockets talk at Rubyconf Uruguay 2010Websockets talk at Rubyconf Uruguay 2010
Websockets talk at Rubyconf Uruguay 2010Ismael Celis
 
The Browser Environment - A Systems Programmer's Perspective [sinatra edition]
The Browser Environment - A Systems Programmer's Perspective [sinatra edition]The Browser Environment - A Systems Programmer's Perspective [sinatra edition]
The Browser Environment - A Systems Programmer's Perspective [sinatra edition]Eleanor McHugh
 
8 Minutes On Rack
8 Minutes On Rack8 Minutes On Rack
8 Minutes On Rackdanwrong
 
Node.js API 서버 성능 개선기
Node.js API 서버 성능 개선기Node.js API 서버 성능 개선기
Node.js API 서버 성능 개선기JeongHun Byeon
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsMichael Peacock
 
Tadhack madrid June 2014: Joris Swinnen and WebRTC Nederland "Invite my colle...
Tadhack madrid June 2014: Joris Swinnen and WebRTC Nederland "Invite my colle...Tadhack madrid June 2014: Joris Swinnen and WebRTC Nederland "Invite my colle...
Tadhack madrid June 2014: Joris Swinnen and WebRTC Nederland "Invite my colle...Bart Uelen
 
HTML5 - The 2012 of the Web
HTML5 - The 2012 of the WebHTML5 - The 2012 of the Web
HTML5 - The 2012 of the WebRobert Nyman
 
feature toggles for ops
feature toggles for opsfeature toggles for ops
feature toggles for opsBram Vogelaar
 

Similar a An Introduction to Faye (20)

Server Side Events
Server Side EventsServer Side Events
Server Side Events
 
[WSO2 Integration Summit Madrid 2019] Integration + Ballerina
[WSO2 Integration Summit Madrid 2019] Integration + Ballerina[WSO2 Integration Summit Madrid 2019] Integration + Ballerina
[WSO2 Integration Summit Madrid 2019] Integration + Ballerina
 
web3j Overview
web3j Overviewweb3j Overview
web3j Overview
 
Practical PHP by example Jan Leth-Kjaer
Practical PHP by example   Jan Leth-KjaerPractical PHP by example   Jan Leth-Kjaer
Practical PHP by example Jan Leth-Kjaer
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 
Top 10 F5 iRules to migrate to a modern load balancing platform
Top 10 F5 iRules to migrate to a modern load balancing platformTop 10 F5 iRules to migrate to a modern load balancing platform
Top 10 F5 iRules to migrate to a modern load balancing platform
 
NodeJS "Web en tiempo real"
NodeJS "Web en tiempo real"NodeJS "Web en tiempo real"
NodeJS "Web en tiempo real"
 
Mashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web AppsMashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web Apps
 
Websockets talk at Rubyconf Uruguay 2010
Websockets talk at Rubyconf Uruguay 2010Websockets talk at Rubyconf Uruguay 2010
Websockets talk at Rubyconf Uruguay 2010
 
Mashing up JavaScript
Mashing up JavaScriptMashing up JavaScript
Mashing up JavaScript
 
MMC Rest API - Servers
MMC Rest API - ServersMMC Rest API - Servers
MMC Rest API - Servers
 
The Browser Environment - A Systems Programmer's Perspective [sinatra edition]
The Browser Environment - A Systems Programmer's Perspective [sinatra edition]The Browser Environment - A Systems Programmer's Perspective [sinatra edition]
The Browser Environment - A Systems Programmer's Perspective [sinatra edition]
 
8 Minutes On Rack
8 Minutes On Rack8 Minutes On Rack
8 Minutes On Rack
 
Node.js API 서버 성능 개선기
Node.js API 서버 성능 개선기Node.js API 서버 성능 개선기
Node.js API 서버 성능 개선기
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friends
 
Tadhack madrid June 2014: Joris Swinnen and WebRTC Nederland "Invite my colle...
Tadhack madrid June 2014: Joris Swinnen and WebRTC Nederland "Invite my colle...Tadhack madrid June 2014: Joris Swinnen and WebRTC Nederland "Invite my colle...
Tadhack madrid June 2014: Joris Swinnen and WebRTC Nederland "Invite my colle...
 
Socket.IO
Socket.IOSocket.IO
Socket.IO
 
HTML5 - The 2012 of the Web
HTML5 - The 2012 of the WebHTML5 - The 2012 of the Web
HTML5 - The 2012 of the Web
 
Payments On Rails
Payments On RailsPayments On Rails
Payments On Rails
 
feature toggles for ops
feature toggles for opsfeature toggles for ops
feature toggles for ops
 

Último

Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)Samir Dash
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAnitaRaj43
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 

Último (20)

Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 

An Introduction to Faye

  • 2. • Publish-subscribe messaging system • Based on the Bayeux protocol • Servers/clients in Ruby and Javascript
  • 3. npm install faye gem install faye
  • 5. var Faye = require('faye') var server = new Faye.NodeAdapter({ mount: '/faye' }) server.listen(8000)
  • 6. require 'faye' server = Faye::RackAdapter.new(:mount => '/faye') server.listen(8000)
  • 8. var Faye = require('faye') var client = new Faye.Client('http://localhost:8000/faye') // subscribe to a channel client.subscribe('/messages', function(message) { console.log('We got a message: ' + message.text) }) // publish to a channel client.publish('/messages', { text: 'HAI!' })
  • 9. <script type="text/javascript" src="http://localhost:8000/faye/client.js"></script> <script type="text/javascript"> var client = new Faye.Client('http://localhost:8000/faye') client.subscribe('/messages', function(message) { alert('We got a message: ' + message.text) }) </script>
  • 10. require 'faye' require 'eventmachine' EM.run { client = Faye::Client.new('http://localhost:8000/faye') # subscribe to a channel client.subscribe('/messages') do |message| puts message.inspect end # publish to a channel client.publish('/messages', { 'text' => 'HAI!' }) }
  • 12. • Simple chat-room application • Sinatra • Faye
  • 13. require 'sinatra' get '/' do erb :index end
  • 14. var Faye = require('faye') var server = new Faye.NodeAdapter({ mount: '/faye' }) server.listen(8000)
  • 15. <!DOCTYPE html> <html> <head> <title>Chattr</title> <link rel="stylesheet" href="chattr.css" type="text/css" media="screen" /> </head> <body> <h1>Lets Chat...</h1> <ul id="chat"></ul> <form id="new_message" action="#" method="get" accept-charset="utf-8"> <input type="text" name="message" id="message" value="" /> <input type="submit" name="send" id="send" value="Send" /> </form> <script src="jquery.min.js" charset="utf-8"></script> <script src="http://localhost:8000/faye/client.js" charset="utf-8"></script> <script src="chattr.js" charset="utf-8"></script> </body> </html>
  • 16. var client = new Faye.Client('http://localhost:8000/faye') // Publish a message... $('#new_message').bind('submit',function() { var now = new Date() var message = { content: $('#message').val(), timestamp: now.getHours() + ":" + now.getMinutes() } client.publish('/messages', message) $('#message').val('') return false }) // Subscribe to message feed... client.subscribe('/messages', function(message) { var str = '' str += '<li>' str += ' <span class="created_at">'+ message.timestamp +'</span>' str += ' '+ message.content str += '</li>' $('#chat').append(str) })
  • 17. Demo
  • 19. Events • handshake • subscribe • unsubscribe • publish • disconnect
  • 20. var Faye = require('faye') var server = new Faye.NodeAdapter({ mount: '/faye' }) server.listen(8000) server.bind('handshake', function(client_id) { console.log("[handshake] - client: '"+ client_id +"'") }) server.bind('subscribe', function(client_id, channel) { console.log("[subscribe] - client: '"+ client_id +"', channel: '"+ channel +"'") }) server.bind('unsubscribe', function(client_id, channel) { console.log("[unsubscribe] - client: '"+ client_id +"', channel: '"+ channel +"'") }) server.bind('publish', function(client_id, channel, data) { console.log("[publish] - client: '"+ client_id +"', channel: '"+ channel +"'") console.log("[publish] - data:") console.log(data) }) server.bind('disconnect', function(client_id) { console.log("[disconnect] - client: '"+ client_id +"'") })
  • 21. require 'faye' require 'logger' Faye::WebSocket.load_adapter('thin') faye = Faye::RackAdapter.new(:mount => '/faye', :timeout => 25) log = Logger.new(STDOUT) log.level = Logger::INFO faye.bind(:handshake) do |client_id| log.info("[handshake] - client: '#{client_id}'") end faye.bind(:subscribe) do |client_id,channel| log.info("[subscribe] - client: '#{client_id}', channel: '#{channel}'") end faye.bind(:unsubscribe) do |client_id,channel| log.info("[unsubscribe] - client: '#{client_id}', channel: '#{channel}'") end faye.bind(:publish) do |client_id,channel,data| log.info("[publish] - client: '#{client_id}', channel: '#{channel}', data: '# {data.inspect}'") end faye.bind(:disconnect) do |client_id| log.info("[disconnect] - client: '#{client_id}'") end run faye
  • 22. Extensions • Override default behaviour... • incoming() • outgoing()
  • 23. Engines • Change the back-end... • faye-redis
  • 24. var faye = require('faye') var faye_redis = require('faye-redis') var server = new faye.NodeAdapter({ mount: '/faye', timeout: 25, engine: { type: faye_redis, host: 'localhost', port: 6379 } }) server.listen(8000)
  • 25. require 'faye' require 'faye-redis' server = Faye::RackAdapter.new( :mount => '/faye', :timeout => 25, :engine => { :type => Faye::Redis, :host => 'localhost', :port => 6379 } ) server.listen(8000)