jetty websocket实现聊天+心跳保持连接

效果图

 

 

1.配置maven需要的jar包-pom.xml

<dependency>
			<groupId>org.eclipse.jetty.websocket</groupId>
			<artifactId>websocket-server</artifactId>
			<version>9.4.9.v20180320</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.eclipse.jetty.websocket</groupId>
			<artifactId>javax-websocket-server-impl</artifactId>
			<version>9.4.9.v20180320</version>
			<scope>provided</scope>
		</dependency>

2.配置jetty插件-pom.xml

<build>
		<outputDirectory>${project.basedir}/src/main/webapp/WEB-INF/classes</outputDirectory>
		<plugins>
			<plugin>
				<groupId>org.eclipse.jetty</groupId>
				<artifactId>jetty-maven-plugin</artifactId>
				<version>9.4.9.v20180320</version>
				<configuration>
					<classesDirectory>${project.basedir}/src/main/webapp/WEB-INF/classes</classesDirectory>
					<!-- 默认值是 0。大于 0 的数值表示开启,0 表示关闭,单位为秒。以配置数值为一个周期,自动的扫描文件检查其内容是否有变化,如果发现文件的内容被改变,则自动重新部署运用。命令行的方式:mvn -Djetty.scanIntervalSeconds=2 jetty:run 。 -->
					<scanIntervalSeconds>0</scanIntervalSeconds>
					<webApp>
					<!-- 配置端口后路径名 -->
						<contextPath>/qfqzServices</contextPath>
					</webApp>
					<httpConnector>
			        <!-- 端口 -->
				      <port>82</port>
				    </httpConnector>
				</configuration>
			</plugin>
		</plugins>
	</build>

3.websocket.java代码

package me.gacl.websocket;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

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

/**
 * @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 */
@ServerEndpoint("/websocket/{userno}")
public class WebSocketTest {
    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
    private static ConcurrentHashMap<String, WebSocketTest> webSocketSet = new ConcurrentHashMap<String, WebSocketTest>();
    
    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;
    //当前发消息的人员编号
    private String userno = "";

    /**
     * 连接建立成功调用的方法
     * @param session  可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
     * @throws UnsupportedEncodingException 
     */
    @OnOpen
    public void onOpen(@PathParam(value = "userno") String param,Session session) throws UnsupportedEncodingException{
    	param = URLDecoder.decode(param, "utf-8");
    	System.out.println(param);
        userno = param;//接收到发送消息的人员编号
        this.session = session;
        webSocketSet.put(param, this); //加入map中
        addOnlineCount();           //在线数加1
        System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(){
        webSocketSet.remove(userno);  //从set中删除
        subOnlineCount();           //在线数减1
        System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     * @param session 可选的参数
     */
    @OnMessage
    public void onMessage(String message, Session session) {
    	System.out.println("来自客户端的消息:" + message);
//      session.get
    	String sendUserno = message.split("[|]")[1];
      
      if (false) {
    	  //群发消息
          sendAll(message);
      } else {
          //给指定的人发消息
          sendToUser(message);
      }
    }
    
    

    /**
     * 给指定的人发送消息
     * @param message
     */
    private void sendToUser(String message) {
        String sendUserno = message.split("[|]")[1];
        String sendMessage = message.split("[|]")[0];
        System.out.println(sendUserno);
        String now = getNowTime();
        try {
            if (webSocketSet.get(sendUserno) != null) {
            	if(sendMessage.equals("在吗")){
            		webSocketSet.get(sendUserno).sendMessage("在");
            	}else{
                    webSocketSet.get(sendUserno).sendMessage(now + "用户" + userno + "发来消息:" + " <br/> " + sendMessage);
            	}
            } else {
                System.out.println("当前用户不在线");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 给所有人发消息
     * @param message
     */
    private void sendAll(String message) {
        String now = getNowTime();
        String sendMessage = message.split("[|]")[0];
        //遍历HashMap
        for (String key : webSocketSet.keySet()) {
            try {
                //判断接收用户是否是当前发消息的用户
                if (!userno.equals(key)) {
                    webSocketSet.get(key).sendMessage(now + "用户" + userno + "发来消息:" + " <br/> " + sendMessage);
                    System.out.println("key = " + key);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    
    /**
     * 获取当前时间
     *
     * @return
     */
    private String getNowTime() {
        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = format.format(date);
        return time;
    }
    /**
     * 发生错误时调用
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error){
        System.out.println("发生错误");
        error.printStackTrace();
    }

    /**
     * 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message) throws IOException{
        this.session.getBasicRemote().sendText(message);
        //this.session.getAsyncRemote().sendText(message);
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketTest.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketTest.onlineCount--;
    }
}

4.前端jsp页面---只拿一个举例

<%@ page language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>WebSocket</title>
</head>
<body>
    Welcome<br/>
            接收人名称:<input id="jsname" type="text"/>
            内容:<input id="text" type="text"/>
    <button onclick="send()">发送消息</button>
    <hr/>
    <!--userno:发送消息人的编号-->
            自己名称:<div id="userno">测试人员1</div>
    <button onclick="closeWebSocket()">关闭WebSocket连接</button>
    <hr/>
    <div id="message"></div>
</body>

<script type="text/javascript">
var lockReconnect = false;  //避免ws重复连接
var userno=document.getElementById('userno').innerHTML;//用户编号
var ws = null;          // 判断当前浏览器是否支持WebSocket
var wsUrl = "ws://192.168.0.113:8080/webSocketTest/websocket/"+userno;
createWebSocket(wsUrl);   //连接ws


function createWebSocket(url) {
    try{
        if('WebSocket' in window){
            ws = new WebSocket(url);
        }else if('MozWebSocket' in window){  
            ws = new MozWebSocket(url);
        }else{
            console.log("您的浏览器不支持websocket协议,建议使用新版谷歌、火狐等浏览器,请勿使用IE10以下浏览器,360浏览器请使用极速模式,不要使用兼容模式!");
        }
        initEventHandle();
    }catch(e){
        reconnect(url);
        console.log(e);
    }     
}


function initEventHandle() {
    ws.onclose = function () {
        reconnect(wsUrl);
        console.log("WebSocket连接关闭!"+new Date().toUTCString());
    };
    ws.onerror = function () {
        reconnect(wsUrl);
        console.log("WebSocket连接发生错误!");
        setMessageInnerHTML("WebSocket连接发生错误");
    };
    ws.onopen = function () {
        heartCheck.reset().start();      //心跳检测重置
        console.log("WebSocket连接成功!"+new Date().toUTCString());
        setMessageInnerHTML("WebSocket连接成功");
    };
    ws.onmessage = function (event) {    //如果获取到消息,心跳检测重置
        heartCheck.reset().start();      //拿到任何消息都说明当前连接是正常的
        console.log("WebSocket收到消息啦:" +event.data);
        if(event.data!="在"){
          setMessageInnerHTML(event.data);
        }
        
    }
}
// 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function() {
    ws.close();
}  

function reconnect(url) {
    if(lockReconnect) return;
    lockReconnect = true;
    setTimeout(function () {     //没连接上会一直重连,设置延迟避免请求过多
        createWebSocket(url);
        lockReconnect = false;
    }, 2000);
}

//心跳检测
var heartCheck = {
    timeout: 10000,        //发一次心跳时间
    timeoutObj: null,
    serverTimeoutObj: null,
    reset: function(){
        clearTimeout(this.timeoutObj);
        clearTimeout(this.serverTimeoutObj);
        return this;
    },
    start: function(){
        var self = this;
        this.timeoutObj = setTimeout(function(){
            //这里发送一个心跳,后端收到后,返回一个心跳消息,
            //onmessage拿到返回的心跳就说明连接正常
            ws.send("在吗|"+userno);
            console.log("在吗")
            self.serverTimeoutObj = setTimeout(function(){//如果超过一定时间还没重置,说明后端主动断开了
                ws.close();     //如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
            }, self.timeout)
        }, this.timeout)
    }
}


//将消息显示在网页上
function setMessageInnerHTML(sendMessage) {
    document.getElementById('message').innerHTML += sendMessage + '<br/>';
}

//关闭WebSocket连接
function closeWebSocket() {
	ws.close();
}

//发送消息
function send() {
    var message = document.getElementById('text').value;//要发送的消息内容
    var jsname = document.getElementById('jsname').value;//接收人
    var now=getNowFormatDate();//获取当前时间
    document.getElementById('message').innerHTML += (now+"发送人:"+userno+'<br/>'+"---"+message) + '<br/>';
    document.getElementById('message').style.color="red";
    var ToSendUserno=jsname;//接收人编号:xxx
    message=message+"|"+ToSendUserno//将要发送的信息和内容拼起来,以便于服务端知道消息要发给谁
    ws.send(message);
}

//获取当前时间
function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
            + " " + date.getHours() + seperator2 + date.getMinutes()
            + seperator2 + date.getSeconds();
    return currentdate;
} 


    
</script>
</html>