Skip to content

Instantly share code, notes, and snippets.

@marcesher
Created August 20, 2012 10:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcesher/3402788 to your computer and use it in GitHub Desktop.
Save marcesher/3402788 to your computer and use it in GitHub Desktop.
websocket chat example
var chatUrl = 'http://'+document.location.hostname+':'+document.location.port+'/GrailsChat/atmosphere/chatty';
class ChatService {
static transactional = false
static atmosphere = [mapping: '/atmosphere/chatty']
def onRequest = { event ->
try {
AtmosphereRequest req = event.request
if (req.method.equalsIgnoreCase("GET")) {
event.suspend()
} else if (req.method.equalsIgnoreCase("POST")) {
String stuff = req.reader.readLine().trim()
event.broadcaster.broadcast(stuff)
}
} catch (Exception e) {
println "ERROR!!!!!"
}
}
def onStateChange = { event ->
AtmosphereResource r = event.resource
AtmosphereResponse res = r.response
try {
if (event.isSuspended()) {
String body = event.message.toString()
String author = body.substring(body.indexOf(":") + 2, body.indexOf(",") - 1);
String message = body.substring(body.lastIndexOf(":") + 2, body.length() - 2);
res.writer.write( createMessage(author, message) )
switch (r.transport()) {
case TRANSPORT.JSONP:
case TRANSPORT.LONG_POLLING:
event.resource.resume()
break
default:
res.writer.flush()
}
} else if (!event.isResuming()) {
event.broadcaster().broadcast( createMessage('someone', 'buh gye') )
}
} catch (Exception e) {
println "ERROR in onStateChange: $e"
}
}
private String createMessage(String author, String text) {
return "{ \"text\" : \"" + text + "\", \"author\" : \"" + author + "\" , \"time\" : " + new Date().time + "}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment