2013-02-27 76 views

回答

1

與碼頭9起,您可以使用WebSocketCreator概念來實現這種行爲。

package org.eclipse.jetty.websocket.server.examples; 

import java.io.IOException; 

import org.eclipse.jetty.websocket.api.UpgradeRequest; 
import org.eclipse.jetty.websocket.api.UpgradeResponse; 
import org.eclipse.jetty.websocket.server.examples.echo.BigEchoSocket; 
import org.eclipse.jetty.websocket.servlet.WebSocketCreator; 
import org.eclipse.jetty.websocket.servlet.WebSocketServlet; 
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory; 

@SuppressWarnings("serial") 
public class MyCustomCreationServlet extends WebSocketServlet 
{ 
    public static class MyCustomCreator implements WebSocketCreator 
    { 
     @Override 
     public Object createWebSocket(UpgradeRequest req, UpgradeResponse resp) 
     { 
      String query = req.getQueryString(); 

      // Start looking at the UpgradeRequest to determine what you want to do 
      if ((query == null) || (query.length() <= 0)) 
      { 
       try 
       { 
        // Let UPGRADE request for websocket fail with 
        // status code 403 (FORBIDDEN) [per RFC-6455] 
        resp.sendForbidden("Unspecified query"); 
       } 
       catch (IOException e) 
       { 
        // An input or output exception occurs 
        e.printStackTrace(); 
       } 

       // No UPGRADE 
       return null; 
      } 

      // Create the websocket we want to 
      if (query.contains("bigecho")) 
      { 
       return new BigEchoSocket(); 
      } 
      else if (query.contains("echo")) 
      { 
       return new MyEchoSocket(); 
      } 

      // Let UPGRADE fail with 503 (UNAVAILABLE) 
      return null; 
     } 
    } 

    @Override 
    public void configure(WebSocketServletFactory factory) 
    { 
     factory.setCreator(new MyCustomCreator()); 
    } 
} 
+0

我不知道factory.setCreator。正是我在找什麼。謝謝。 – fso 2013-02-28 06:39:43