websocket可以实现服务端的消息推送,而不必在客户端轮询,大大的节省的资源,对于实时通讯来说简直是个大喜讯。
在上一篇文章中介绍了协议握手,这篇文章将通过实现简单的群聊来帮助进一步了解websocket。
注意:1.JavaEE版本为7.0
2.tomcat版本为8.0
3.不需要额外导入其他的jar包
由于websocket不支持低版本的javaEE和tomcat,所以必须符合上述条件,我是在Myeclipse2014 的IDE中进行编码的。
为了尽可能的使代码简洁以便更好的理解,所以代码中有些地方可能不全面,但不影响学习websocket。
首先是WebSocketServer类:
package socket;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.servlet.http.HttpSession;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint(value = "/socket",configurator=GetHttpSessionConfigurator.class)
public class WebSocketServer {
private static final Set<WebSocketServer> onlineUsers =
new CopyOnWriteArraySet<WebSocketServer>(); //静态变量 存储在线用户
private HttpSession httpSession;
private Session session;
private String name;
@OnMessage
public void onMessage(String message, Session session)
throws IOException, InterruptedException {
//将客户端传来的消息发送给所有在线用户
sendMessageToAllOnline(session,this.name+" : "+message);
//在控制台打印当