Created
July 7, 2012 01:52
-
-
Save chitan/3063806 to your computer and use it in GitHub Desktop.
How to use WebSocket of Jetty
This file contains hidden or 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
//This sample is how to use websocket of Jetty. | |
package wsapp; | |
import java.io.IOException; | |
import java.util.ArrayList; | |
import javax.servlet.http.HttpServletRequest; | |
import org.eclipse.jetty.websocket.WebSocket; | |
import org.eclipse.jetty.websocket.WebSocketServlet; | |
public class WsChatServlet extends WebSocketServlet { | |
private static final long serialVersionUID = 1; | |
private static ArrayList<MySocket> mslist = new ArrayList<MySocket>(); | |
public WebSocket doWebSocketConnect(HttpServletRequest req, String str) { | |
return new MySocket(); | |
} | |
private class MySocket implements WebSocket.OnTextMessage { | |
protected Connection con; | |
@Override | |
public void onOpen(Connection connection) { | |
try { | |
this.con = connection; | |
con.sendMessage("Hello!"); | |
mslist.add(this); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
@Override | |
public void onClose(int i, String s) { | |
mslist.remove(this); | |
} | |
@Override | |
public void onMessage(String s) { | |
for (MySocket socket : mslist) { | |
try { | |
socket.con.sendMessage(s); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment