Created
August 20, 2012 10:06
-
-
Save marcesher/3402788 to your computer and use it in GitHub Desktop.
websocket chat example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var chatUrl = 'http://'+document.location.hostname+':'+document.location.port+'/GrailsChat/atmosphere/chatty'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ChatService { | |
static transactional = false | |
static atmosphere = [mapping: '/atmosphere/chatty'] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!!!!!" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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