WebSocket实现长连接实时消息推送

本文详细介绍了WebSocket技术,包括其在Web浏览器与服务器之间的双向通信作用,以及如何基于Java实现WebSocket服务端点。通过POM文件添加依赖,创建WebSocket服务端点工具类,并展示在具体业务中如何运用WebSocket进行消息推送。同时,给出了前端页面的JavaScript代码示例,展示了如何建立WebSocket连接并接收服务器消息。
摘要由CSDN通过智能技术生成

WebSocket用于在Web浏览器和服务器之间进行任意的双向数据传输的一种技术。WebSocket协议基于TCP协议实现,包含初始的握手过程,以及后续的多次数据帧双向传输过程。其目的是在WebSocket应用和WebSocket服务器进行频繁双向通信时,可以使服务器避免打开多个HTTP连接进行工作来节约资源,提高了工作效率和资源利用率。

1.POM文件添加依赖包

<dependency>
    <groupId>javax.websocket</groupId>
    <artifactId>javax.websocket-api</artifactId>
    <version>1.1</version>
    <scope>provided</scope>
 </dependency>

2.后台webSocket 服务端点工具类

package com.zyf.test.util;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import com.alibaba.fastjson.JSONObject;
import com.zyf.test.common.StringUtil;


@ServerEndpoint("/websocket/{username}")
public class WebSocketUtil {
	
	private static int onlineCount = 0;
	private static Map<String, WebSocketUtil> clients = new ConcurrentHashMap<String, WebSocketUtil>();
	private Session session;
	private String username;
	
	@OnOpen
	public void onOpen(@PathParam("username") String username, Session session) throws IOException {
		this.username = username;
		this.session = session;
		addOnlineCount();
		clients.put(username, this);
		System.out.println(username+"已连接,当前连接数:"+getOnlineCount());
	}

	@OnClose
	public void onClose() throws IOException {
		clients.remove(username);
		subOnlineCount();
	}
	
	@OnMessage
	public void onMessage(String message) throws IOException {
		if(StringUtil.isNotEmpty(message)){
			JSONObject jsonTo = JSONObject.parseObject(message);
			if (!jsonTo.get("To").equals("All")) {
				sendMessageTo("给一个人", jsonTo.get("To").toString());
			} else {
				sendMessageAll("给所有人");
			}
		}
	}
	
	@OnError
	public void onError(Session session, Throwable error) {
		error.printStackTrace();
	}
	
	public void sendMessageTo(String message, String To) throws IOException {
		for (WebSocketUtil item : clients.values()) {
			String client = item.username.split("_")[0];
			if (client.equals(To)){
				item.session.getAsyncRemote().sendText(message);
				System.out.println("已给用户["+item.username+"]发送信息完毕!");
			}
		}
	}
	
	public void sendMessageAll(String message) throws IOException {
		for (WebSocketUtil item : clients.values()) {
			item.session.getAsyncRemote().sendText(message);
		}
	}
	
	public static synchronized int getOnlineCount() {
		return onlineCount;
	}
	
	public static synchronized void addOnlineCount() {
		WebSocketUtil.onlineCount++;
	}
	
	public static synchronized void subOnlineCount() {
		WebSocketUtil.onlineCount--;
	}

	public static synchronized Map<String, WebSocketUtil> getClients() {
		return clients;
	}
	
}

3.具体业务中应用,此处根据自身业务使用

//业务代码,例如:前台发起二维码扫码实名认证请求,需要后台认证完成后主动推送消息给前台修改二维码状态
WebSocketUtil webSocketUtil = new WebSocketUtil();
String message = "";//此处是传递给前台的数据,可以是json串,方便前端解析
String to="张三";//此参数为前端要接收信息的用户
try {
        webSocketUtil.sendMessageTo(message, to);
    } catch (IOException e) {
			e.printStackTrace();
        logger.error("给前台用户发送信息失败,异常:{}",e);
    }
//自己的业务处理代码

4.前端页面

var websocket = null;
//username 参数为客户端发起后台请求链接的用户
//初始链接之前二维码状态为未认证,
$("#verifyTs").html("未认证");
function verify(username) {
	var protocol = window.location.protocol;
	var webscoketProtocol="ws:";
	if("https:"==protocol){
		webscoketProtocol="wss:";
	}
	if('WebSocket' in window){
		var url = webscoketProtocol+'//' + window.location.host + projectName+'/websocket/'+username;
		websocket = new WebSocket(url);      //打开WebSocket
    }else{
    	alert("你的浏览器不支持WebSocket");
    }
	//连接发生错误的回调方法  
	websocket.onerror = function() {  
	    alert("WebSocket连接发生错误,请稍后再试!");
	    console.log(username+"WebSocket连接发生错误,请稍后再试!");
	};
	websocket.onopen = function() {
		console.log(username+"WebSocket连接成功");
//    	sock.send(JSON.stringify());//客户端发送消息
    };
    websocket.onmessage = function(e) {//接收消息
	    e = e || event;
	    var message = e.data;
		console.log(username+"接收到消息:"+message);
		//根据不同状态操作二维码
		if(message!=null){
			var verifyData=JSON.parse(message);
			if(verifyData!=null){
				var status=verifyData.statusCode;
				if(status==1){
					$("#verifyTs").html("认证通过");
					$("#srrzQrCodeDiv").attr("style","display:none;");
					applyFallBack();
				}else if(status==2){
					$("#verifyTs").html("认证未通过,原因:"+verifyData.auditConclusions);
				}else if(status==0){
					$("#verifyTs").html("认证中");
				}else{
					$("#verifyTs").html("未认证");
				}
			}
		}
    };
    websocket.onclose = function() {         //处理连接关闭事件
    	console.log(username+"WebSocket连接关闭");
    };
    window.onbeforeunload = function() {  
		 websocket.close();
	};
}

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

跟着飞哥学编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值