Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Websocket in scala / akka / play

I would like to create a simple Websocket application using Scala / Akka / Play.

What I see from the examples (such as the webchat or the recent talk at the Scala Days), is a blend between JavaScript / Coffeescript, html templates and so on.

The clients of my Websocket application will be also native mobile apps (Android, iOS), so I need to think "out of the browser".

How can I create a websocket application that can simply push a "hello" string?

like image 995
ticofab Avatar asked Jul 20 '13 10:07

ticofab


Video Answer


2 Answers

There are two parts in a WebSocket connection: the server and the client. You could just make the server part using Play2 and implement a client with Android (see websocket-android-phonegap), iOS (see Unitt), javascript app...

Here is an example for a very basic websocket connection taken from http://blog.tksfz.org/2012/10/12/websockets-echo-using-play-scala-and-actors-part-i/:

package controllers

import play.api.mvc._

object Application extends Controller {
  def index = WebSocket.using[String] {
    val out = Enumerator.imperative[String]()
    val in = Iteratee.foreach[String] {
      msg =>
        out.push(msg)
    }
    (in, out)
  }
}

You only have to set a route that points to your controller conf/routes:

GET /connect  Application.index

The server is ready to run. You can then connect to your WebSocket with a javascript application, an Android application, etc... The client side is another matter.

If you use chrome or chromium, just open your javascript console in developer tools and you can connect to your server just like that:

ws = new WebSocket('ws://localhost:9000/connect')
ws.onmessage = function( message ) { console.log( message ); };
ws.send('test')

It will send you back your message and log it in the javascript console whenever you send one.

You could also just use the http://www.websocket.org/echo.html echo test and feed it your 'ws://localhost:9000/connect' url.

like image 86
mor Avatar answered Oct 05 '22 12:10

mor


Either you could use a pain old Socket, but you'll have problems with port forwarding (ie through firewalls) or you can could use Websocket client library, such as this one in Java :http://www.eclipse.org/jetty/documentation/current/jetty-websocket-client-api.html

like image 20
ndeverge Avatar answered Oct 05 '22 13:10

ndeverge