这是 Jetty 上的示例 WebSocket Servlet 实现:
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.websocket.WebSocket;
import org.eclipse.jetty.websocket.WebSocketFactory;
public class SampleServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private WebSocketFactory wsFactory;
private final Set<SampleWebSocket> members = new CopyOnWriteArraySet<SampleWebSocket>();
@Override
public void init() throws ServletException {
wsFactory = new WebSocketFactory( new WebSocketFactory.Acceptor() {
@Override
public boolean checkOrigin( final HttpServletRequest request, final String origin ) {
// Allow all origins
return true;
}
@Override
public WebSocket doWebSocketConnect( final HttpServletRequest request, final String protocol ) {
return new SampleWebSocket();
}
} );
wsFactory.setBufferSize( 4096 );
wsFactory.setMaxIdleTime( 60000 );
}
@Override
protected void doGet( final HttpServletRequest request, final HttpServletResponse response ) throws IOException {
if ( wsFactory.acceptWebSocket( request, response ) ) {
return;
}
response.sendError( HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Websocket only" );
}
public class SampleWebSocket implements WebSocket.OnTextMessage {
private volatile Connection connection;
public SampleWebSocket( ) {
}
@Override
public void onClose( final int closeCode, final String message ) {
members.remove( this );
System.out.println( "onClose: closeCode=" +closeCode+ ", message: '" +message+ "'" );
}
@Override
public void onOpen( final Connection connection ) {
this.connection = connection;
System.out.println( "onOpen: connection=" +connection );
members.add( this );
// Send sample binary message back
try {
connection.sendMessage( "Sample message" );
} catch ( final IOException e ) {
e.printStackTrace();
}
}
@Override
public void onMessage( final String data ) {
System.out.println( "onMessage: data=" +data );
// Relay message to other connected clients
for ( final SampleWebSocket member: members ) {
try {
member.connection.sendMessage( data );
} catch ( final IOException e ) {
e.printStackTrace();
}
}
}
}
}