Created
June 10, 2013 07:24
-
-
Save ankurtrapasiya/5747068 to your computer and use it in GitHub Desktop.
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
public class SocketServlet extends WebSocketServlet { | |
private static final long serialVersionUID = 1L; | |
private static final String GUEST_PREFIX = "Guest"; | |
private final AtomicInteger connectionIds = new AtomicInteger(0); | |
private final Set<ChatMessageInbound> connections = | |
new CopyOnWriteArraySet<ChatMessageInbound>(); | |
public SocketServlet() { | |
super(); | |
} | |
@Override | |
protected StreamInbound createWebSocketInbound(String arg0, HttpServletRequest arg1) { | |
return new ChatMessageInbound(connectionIds.incrementAndGet()); | |
} | |
private final class ChatMessageInbound extends MessageInbound | |
{ | |
private final String nickname; | |
private ChatMessageInbound(int id) | |
{ | |
this.nickname=GUEST_PREFIX +id; | |
} | |
@Override | |
protected void onBinaryMessage(ByteBuffer arg0) throws IOException { | |
throw new UnsupportedOperationException( | |
"Binary message not supported."); | |
} | |
@Override | |
protected void onTextMessage(CharBuffer arg0) throws IOException { | |
String message=String.format("%s : %s",nickname,arg0.toString()); | |
broadcast(message); | |
} | |
@Override | |
protected void onClose(int status) { | |
connections.remove(this); | |
String message=String.format("%s %s",nickname," left the chat"); | |
broadcast(message); | |
} | |
@Override | |
protected void onOpen(WsOutbound outbound) { | |
connections.add(this); | |
String message=String.format("%s %s", nickname," has joined"); | |
broadcast(message); | |
} | |
private void broadcast(String message) | |
{ | |
for(ChatMessageInbound connection:connections) | |
{ | |
try | |
{ | |
CharBuffer buff=CharBuffer.wrap(message); | |
connection.getWsOutbound().writeTextMessage(buff); | |
} | |
catch(IOException ex) | |
{ | |
ex.printStackTrace(); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment