Date: 2015jan24
Language: Java
Product: Jetty8
Q. Jetty: How can I do websockets with Jetty8?
A. The java code:
package com.example;
import javax.servlet.*;
import javax.servlet.http.*;
import org.eclipse.jetty.websocket.WebSocket;
import org.eclipse.jetty.websocket.WebSocketServlet;
import java.io.IOException;
public class Echo extends WebSocketServlet {
// Not necessary
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException ,IOException {
getServletContext().getNamedDispatcher("default").forward(request,response);
}
@Override
public WebSocket doWebSocketConnect(HttpServletRequest request, String protocol) {
return new EchoWebSocket();
}
private class EchoWebSocket implements WebSocket, WebSocket.OnTextMessage {
private Connection mConnection;
void send(String txt) {
try {
mConnection.sendMessage(txt);
}
catch(IOException ex) {
System.out.println(ex.toString());
}
}
@Override
public void onOpen(Connection conn) {
mConnection = conn;
System.out.println("onOpen");
send("HELLO FROM OPEN");
}
@Override
public void onClose(int arg0, String arg1) {
System.out.println("onClose");
}
@Override
public void onMessage(String txt) {
System.out.println("got " + txt);
send("HELLO, YOU SENT " + txt);
}
}
}
web.xml:
<servlet>
<servlet-name>Echo</servlet-name>
<servlet-class>com.example.Echo</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Echo</servlet-name>
<url-pattern>/echo/*</url-pattern>
</servlet-mapping>
The browser side:
<script>
var ws;
function go() {
ws = new WebSocket("ws://localhost:8080/echo");
ws.onopen = onOpen;
ws.onmessage = onMessage;
ws.onclose = onClose;
}
function onOpen() {
console.log('onOpen');
ws.send('from the js');
}
function onClose() {
console.log('onClose');
}
function onMessage(m) {
console.log('onMessage data=' + m.data);
}
</script>
<button onClick="go()">Go</button>