WebSocket

一、服务端

package com.feng.web;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

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;

/**
 * @ServerEndpoint注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端
 * @author fengzp
 *
 */
@ServerEndpoint(value = "/websocket")
public class WebSocketSession{
    
    private static int onlineCount = 0;
    
    /**
     * 用来记录每一连接的线程安全集合
     */
    private static CopyOnWriteArraySet<WebSocketSession> webSocketSessionSet = new CopyOnWriteArraySet<WebSocketSession>();
    
    private Session session;
    
    /**
     * 成功建立连接时调用
     * @param session
     */
    @OnOpen
    public void come(Session session){
        this.session = session;
        webSocketSessionSet.add(this);
        WebSocketSession.addCount();
        System.out.println("进来了, 当前人数:"+WebSocketSession.getCount());
    }
    
    /**
     * 连接断开时调用
     */
    @OnClose
    public void leave(){
        webSocketSessionSet.remove(this);
        WebSocketSession.subCount();
        System.out.println("离开了, 当前人数:"+WebSocketSession.getCount());
    }
    
    /**
     * 收到信息时调用
     * @param message
     * @param session
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("信息来了:"+message);
        for(WebSocketSession s : webSocketSessionSet){
            try {
                s.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }
    }
    
    /**
     * 发生错误时调用
     * @param session
     * @param error
     */
    @OnError
    public void error(Session session, Throwable error){
        System.out.println("发送错误了");
        error.printStackTrace();
    }
    
    public void sendMessage(String msg) throws IOException{
        this.session.getBasicRemote().sendText(msg);
    }
    
    public static synchronized void addCount(){
        WebSocketSession.onlineCount++;
    }
    
    public static synchronized void subCount(){
        WebSocketSession.onlineCount--;
    }
    
    public static int getCount(){
        return WebSocketSession.onlineCount;
    }
}

 

二、客户端

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/jquery-2.2.3.js"></script>
<script type="text/javascript">
    var websocket = null;
    if('WebSocket' in window){
        websocket = new WebSocket("ws://localhost:8080/JavaWebSocket/websocket");
    }else{
        alert("当前浏览器不支持websocket");
    }

    //连接成功建立的回调方法
    websocket.onopen = function () {
         setMessageInnerHTML("WebSocket连接成功");
     }
 
     //接收到消息的回调方法
     websocket.onmessage = function (event) {
         setMessageInnerHTML(event.data);
     }
 
     //连接关闭的回调方法
     websocket.onclose = function () {
         setMessageInnerHTML("WebSocket连接关闭");
     }
 
     //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
     window.onbeforeunload = function () {
         closeWebSocket();
     }
     
     //关闭WebSocket连接
     function closeWebSocket() {
         websocket.close();
     }
     
        function send(){
            var text = $("#text").val();
            websocket.send(text); 
        }
        
       function setMessageInnerHTML(html){
        $("#message").html($("#message").html()+html+'<br/>');
    }
</script>
<title>Insert title here</title>
</head>
<body>
    <input id="text" type="text"/><br/>
    <button onclick="send()">发送</button>
    <button onclick="closeWebSocket()">关闭</button>
    <div id="message"></div>
</body>
</html>

 

三、模拟多客户端进行测试

posted @ 2016-05-13 14:38  fengzp  阅读(258)  评论(0编辑  收藏  举报