Websockets Tomcat 7在现有项目

时间:2016-05-18 14:35:16

标签: java eclipse tomcat websocket java-websocket

我尝试在Tomcat6上运行的Java项目中运行websocket服务器。我已经设置了一个运行该项目的Tomcat 7服务器。 首先,我尝试运行Tomcat7的套接字示例。这完美运行。我把这个类复制到了我的旧项目中。当我再次运行旧项目时,所有功能都像以前一样工作,但只有websocket服务器不起作用。

这是我从Tomcat到旧项目的示例中复制的ChatAnnotation类。

import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.apache.log4j.Logger;

@ServerEndpoint(value = "/websocket/chat")
public class ChatAnnotation {
    private static Logger logger = Logger.getLogger(ChatAnnotation.class);

    private static final String GUEST_PREFIX = "Guest";
    private static final AtomicInteger connectionIds = new AtomicInteger(0);
    private static final Set<ChatAnnotation> connections = new CopyOnWriteArraySet<ChatAnnotation>();

    private final String nickname;
    private Session session;

    public ChatAnnotation() {
        nickname = GUEST_PREFIX + connectionIds.getAndIncrement();
        logger.info("ws instance");
    }

    @OnOpen
    public void start(Session session) {
        this.session = session;
        connections.add(this);
        String message = String.format("* %s %s", nickname, "has joined.");
        broadcast(message);
    }

    @OnClose
    public void end() {
        connections.remove(this);
        String message = String.format("* %s %s", nickname, "has disconnected.");
        broadcast(message);
    }

    @OnMessage
    public void incoming(String message) {
        // Never trust the client
        String filteredMessage = String.format("%s: %s", nickname, message.toString());
        broadcast(filteredMessage);
    }

    @OnError
    public void onError(Throwable t) throws Throwable {
        logger.error("Chat Error: " + t.toString(), t);
    }

    private static void broadcast(String msg) {
        for (ChatAnnotation client : connections) {
            try {
                synchronized (client) {
                    client.session.getBasicRemote().sendText(msg);
                }
            } catch (IOException e) {
                logger.debug("Chat Error: Failed to send message to client", e);
                connections.remove(client);
                try {
                    client.session.close();
                } catch (IOException e1) {
                    // Ignore
                }
                String message = String.format("* %s %s", client.nickname, "has been disconnected.");
                broadcast(message);
            }
        }
    }
}

我在web.xml中添加了。在我的旧项目中也使用tcpsockets这可能是问题吗? 任何人都可以帮我解决这个问题吗?

修改 增加的课程:

import java.util.HashSet;
import java.util.Set;

import javax.websocket.Endpoint;
import javax.websocket.server.ServerApplicationConfig;
import javax.websocket.server.ServerEndpointConfig;

import org.apache.log4j.Logger;

public class ExamplesConfig implements ServerApplicationConfig {

    private static Logger log = Logger.getLogger(ChatAnnotation.class);

    public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> endpointClasses) {
        Set<ServerEndpointConfig> result = new HashSet<ServerEndpointConfig>();
        log.info("getEndpointConfigs");
        return result;
    }

    public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> scanned) {
        log.info("getAnnotatedEndpointClasses");            
        return scanned;
    }
}

1 个答案:

答案 0 :(得分:0)

Java websocket服务器使用ServerApplicationConfig interface的返回值来部署程序化端点和已注释的端点。 对于Tomcat示例,如果您更改ChatAnnotation包名称。您还必须修改websocket.ExamplesConfig

public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> scanned) {
    // Deploy all WebSocket endpoints defined by annotations in the examples
    // web application. Filter out all others to avoid issues when running
    // tests on Gump
    Set<Class<?>> results = new HashSet<>();
    for (Class<?> clazz : scanned) {
        String name = clazz.getPackage().getName();
        boolean ok = name.startsWith("websocket.");
        if (ok) {
            results.add(clazz);
        }
    }
    return scanned;
}

getAnnotatedEndpointClasses(scanned)只返回包名称以 websocket开头的类。即使他们有@ServerEndpoint声明,也不会部署不匹配的类。