Tomcat官网上的Websocket例子

这段时间,我看了一段时间关于webRTC的资料和websocket的资料,在这里分享一下;

websocket发布到1.0了,最新的tomcat7也支持了websocket,我现在用的7.052可以支持了,之前的tomcat-7.0.42好像还不支持websocket,所有下载最新的websocket就可以了


关于tomcat的websocketAPI:

在官网上写到:

Prior to the development of JRS-356, Tomcat provided a proprietary WebSocket API. This API has been deprecated in Tomcat 7 and will be removed in Tomcat 8. There is unlikely to be any further development of this proprietary API apart from bug fixes.

For information on this API, please see the Javadoc for the org.apache.catalina.websocket package.

可以看出org.apache.catalina.websocket这个包已经废弃了,网上有些资料没有更新,可能会用到这个包。这个包在tomcat8中不能使用

现在我们用到的tomcat的websocket包都在在javax.websocket这个包里面
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;

下面这个例子就是tomcat上面的例子


package websocket.chat;

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.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import util.HTMLFilter;


@ServerEndpoint(value = "/websocket/chat")
public class ChatAnnotation {

    private static final Log log = LogFactory.getLog(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();
    }

    /*当websocket的客户端连接到服务器时候,这个方法就会执行,并且传递一个session会话对象来
     我们拿到这话session,就是可以给客户端发送消息*/
    @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, HTMLFilter.filter(message.toString()));
        broadcast(filteredMessage);
    }

    /*发生了异常自动执行*/
    @OnError
    public void onError(Throwable t) throws Throwable {
        log.error("Chat Error: " + t.toString(), t);
    }

    /*广播:遍历客户端集,发送消息,注意发送要用的session,用session.getBasicRemote().sendText(msg)发送消息*/
    private static void broadcast(String msg) {
        for (ChatAnnotation client : connections) {//遍历所有
            try {//如果这个client已经在线
                synchronized (client) {
                    client.session.getBasicRemote().sendText(msg);//发送消息
                }
            } catch (IOException e) {//如果这个client不在线
                log.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);
            }
        }
    }
}


我改动了一些的demo

源码下载[百度网盘]


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值