Skip to content

Getting started with Amber and socket.io

sl4m edited this page Apr 1, 2012 · 1 revision

Here's a rough-cut of using socket.io with Amber:

  1. Install Node.js in the appropiate way for your plattform.

  2. Install socket.io using npm. If that fails, download it manually and set your node module path like so:

     export NODE_PATH=$NODE_PATH:/your/path/to/socket.io/
    
  3. Create a server-script in node.js for example by subclassing FileServer and create a start-method:

     YourFileServer>>start
     	(httpServer := http createServer: [:request :response |
     	 	self handleRequest: request respondTo: response]) listen: self port.
     	self setupSocketIO.`
    
  4. Create a socket setup method:

     YourFileServer>>setupSocketIO
         | iopath |
         "Require with just the name did not work for me, I had to specify the path manually"
         iopath := '/Network/Servers/Eskridge/Projects/Amber/amber/.node_modules/socket.io/index'.
    
         "Mount socket.io to the httpServer created in #start"
         io := (self require: iopath) listen: httpServer.
    
         "Define the behaviour of the socket"
         io sockets on: 'connection' do: [:socket|    
             "socket gives you the handle to the socket. you can store that for later"   
                       
             "specify the events you want to distribute here"
             socket on: 'NewsPosted' do: [ :eventInfo | 
                 "Here I just recast it"
                 socket emit: 'NewsPosted' withData: eventInfo. 
             ].
         ].
    
  5. On the client Insert into the head of your html:

     <script src="/socket.io/socket.io.js"></script>
    
  6. Establish the connection & event-handling

     ClientController>>establishConnection
     	self socket: (io connect: 'http://your-url-and-server:port').
    
             "You can specify all the events you want to handle this way or write a method for it"
         	self socket on: 'NewsPosted' do: [:data | window alert: data].
    
     "convinience method for the specification of events to handle"
     ClientController>>on: anEvent do: anUnaryBlock
             self socket on: anEvent do: [:eventInfoString | 
                 anUnaryBlock value: (JSON parse: eventInfoString) ].
    
  7. And send data:

     ClientController>>postNews: jsonData
         self socket emit: 'NewsPosted' with: jsonData.