java websocket如何配置_Java -- springboot 配置 Websocket

1.配置依赖

org.springframework.boot

spring-boot-starter-websocket

2、配置类

package com.vim.common.config;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration

public class WebSocketConfig {

@Bean

public ServerEndpointExporter serverEndpointExporter() {

return new ServerEndpointExporter();

}

}

3、消息类别

package com.vim.common.push;

public class WebSocketMsg {

public enum MsgType{

ONLINE_COUNT, NOTIFY;

}

/**

* 消息类型

*/

private MsgType type;

/**

* 消息内容

*/

private Object data;

public WebSocketMsg(MsgType type, Object data) {

this.type = type;

this.data = data;

}

public MsgType getType() {

return type;

}

public void setType(MsgType type) {

this.type = type;

}

public Object getData() {

return data;

}

public void setData(Object data) {

this.data = data;

}

}

4、消息服务器

package com.vim.common.push;

import com.alibaba.fastjson.JSONObject;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;

import javax.websocket.OnOpen;

import javax.websocket.Session;

import javax.websocket.server.PathParam;

import javax.websocket.server.ServerEndpoint;

import java.util.HashSet;

import java.util.concurrent.atomic.AtomicLong;

@ServerEndpoint("/websocket/{userId}")

@Component

public class WebSocketServer {

private static final Logger logger = LoggerFactory.getLogger(WebSocketServer.class);

private Session session;

private String userId;

public String getUserId() {

return userId;

}

public void setUserId(String userId) {

this.userId = userId;

}

/**

* 在线人数

*/

private static AtomicLong onlineCount = new AtomicLong(0);

/**

* 客户端集合

*/

private static HashSet servers = new HashSet<>();

@OnOpen

public void onOpen(Session session, @PathParam("userId") String userId) {

this.session = session;

this.userId = userId;

boolean online = false;

for(WebSocketServer server:servers){

if(server.getUserId().equals(userId)){

online = true;

}

}

if(!servers.contains(this) && !online){

servers.add(this);

onlineCount.incrementAndGet();

sendMessage(new WebSocketMsg(WebSocketMsg.MsgType.ONLINE_COUNT, onlineCount.get()));

}

}

@OnClose

public void onClose() {

servers.remove(this);

onlineCount.decrementAndGet();

sendMessage(new WebSocketMsg(WebSocketMsg.MsgType.ONLINE_COUNT, onlineCount.get()));

}

/**

* 发送消息到指定用户

*/

public static void sendMessage(WebSocketMsg message, String userId) {

for (WebSocketServer server : servers) {

try {

if(server.getUserId().equals(userId)){

server.session.getBasicRemote().sendText(JSONObject.toJSONString(message));

}

} catch (Exception e) {

logger.error("系统异常!", e);

}

}

}

/**

* 群发消息

*/

public static void sendMessage(WebSocketMsg message) {

for (WebSocketServer server : servers) {

try {

server.session.getBasicRemote().sendText(JSONObject.toJSONString(message));

} catch (Exception e) {

logger.error("系统异常!", e);

}

}

}

}

5、html代码

通用项目模板

var websocket = null;

if ('WebSocket' in window) {

websocket = new WebSocket("ws://"+window.location.host+"/websocket/11");

}

websocket.onopen = onOpen;

websocket.onmessage = onMessage;

websocket.onerror = one rror;

websocket.onclose = onClose;

function onMessage(event) {

var result = JSON.parse(event.data);

if(result.type == "ONLINE_COUNT"){

}

if(result.type == "NOTIFY"){

}

}

function onOpen(event) {}

function one rror() {}

function onClose() {}

标签:Java,springboot,Websocket,userId,server,import,websocket,type,public

来源: https://blog.csdn.net/sky_eyeland/article/details/98969660

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值