使用springCloud + uni-app +websocket配置消息推送服务

后端代码
服务配置类

@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}

webSocket 业务类

@ServerEndpoint(value = "/client")
@Component
@Slf4j
public class CustomerPhonePushSocket {

    // 静态变量,用来记录当前在线连接数。应该设计成线程安全的
    private static int onlineCount = 0;

    // concurrent包的线程安全Set,用来存放每个客户端对应的MyWebsocket对象
    private static CopyOnWriteArraySet<CustomerPhonePushSocket> wsClientMap = new CopyOnWriteArraySet<>();

    // 与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;

    /**
     * 链接成功调用此方法
     * @param applyId
     * @param session
     */
    @OnOpen
    public void onOpen(@PathParam("applyId")String applyId,Session session){
        this.session = session;
        wsClientMap.add(this);
        addOnlineCount();
        log.info(session.getId()+"有新链接加入,当前链接数为:" + wsClientMap.size());

    }

    /**
     * 关闭链接
     */
    @OnClose
    public void onClose(){
        wsClientMap.remove(this);
        subOnlineCount();
        log.info("有链接断开,当前链接数为:" + wsClientMap.size());
    }

    /**
     * 收到客户端的消息
     * @param message
     * @param session
     */
    @OnMessage
    public void onMessage(String message,Session session) throws IOException {
        log.info("来自终端的消息:" + message);
        message = "来自服务器的消息:" + message;
        sendMsgToAll(message);
    }

    /**
     * 给所有的客户端发送消息
     * @param message
     * @throws IOException
     */
    public void sendMsgToAll(String message) throws IOException {
        for (CustomerPhonePushSocket a : wsClientMap) {
            // 艹  forEach写法sendText 异常无法抛出去
            a.session.getBasicRemote().sendText(message);
        }
        log.info("成功发送一条信息" + message);
    }

    /**
     * 给指定客户发送消息
     * @param message
     * @throws IOException
     */
    public void sendMessage (String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
        log.info("成功发送一条信息" + message);
    }

    public static synchronized int getOnlineCount(){
        return CustomerPhonePushSocket.onlineCount;
    }
    public static synchronized void addOnlineCount() {
        CustomerPhonePushSocket.onlineCount++;
    }

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


}

=============================================================================
uni-app 前端代码

<template>
	<view>
		<page-head title="websocket通讯示例"></page-head>
		<view class="uni-padding-wrap">
			<view class="uni-btn-v">
				<view class="websocket-msg">{{showMsg}}</view>
				<button type="primary" @click="connect">连接websocket服务</button>
				<button v-show="connected" type="primary" @click="send">发送一条消息</button>
				<button type="primary" @click="close">断开websocket服务</button>
				<view class="websocket-tips">发送消息后会收到一条服务器返回的消息(与发送的消息内容一致)</view>
			</view>
		</view>
	</view>
</template>

<script>
	let platform = uni.getSystemInfoSync().platform
	export default {
		data() {
			return {
				connected: false,
				connecting: false,
				socketTask: false,
				msg: false,
			}
		},
		computed: {
			showMsg() {
				if (this.connected) {
					if (this.msg) {
						return '收到消息:' + this.msg
					} else {
						return '等待接收消息'
					}
				} else {
					return '尚未连接'
				}
			}
		},
		onUnload() {
			console.log("=======================onUnload======================")
            uni.hideLoading()
			if (this.socketTask && this.socketTask.close) {
				this.socketTask.close()
			}
		},
		methods: {
			connect() {
				if (this.connected || this.connecting) {
					uni.showModal({
						content: '正在连接或者已经连接,请勿重复连接',
						showCancel: false
					})
					return false
				}
				this.connecting = true
				uni.showLoading({
					title: '连接中...'
				})
				this.socketTask = uni.connectSocket({
					url: 'ws://localhost:8080/gcrm/client',
					data() {
						return {
							msg: 'Hello'
						}
					},
					// #ifdef MP
					header: {
						'content-type': 'application/json'
					},
					// #endif
					// #ifdef MP-WEIXIN
					method: 'GET',
					// #endif
					success(res) {
						// 这里是接口调用成功的回调,不是连接成功的回调,请注意
					},
					fail(err) {
						// 这里是接口调用失败的回调,不是连接失败的回调,请注意
					}
				})
                console.log(this.socketTask);
				this.socketTask.onOpen((res) => {
					this.connecting = false
					this.connected = true
					uni.hideLoading()
					uni.showToast({
						icon: 'none',
						title: '连接成功'
					})
					console.log('onOpen', res);
				})
				this.socketTask.onError((err) => {
					this.connecting = false
					this.connected = false
					uni.hideLoading()
					uni.showModal({
						content: '连接失败,可能是websocket服务不可用,请稍后再试',
						showCancel: false
					})
					console.log('onError', err);
				})
				this.socketTask.onMessage((res) => {
					this.msg = res.data
					console.log('onMessage', res)
				})
				this.socketTask.onClose((res) => {
					this.connected = false
					this.startRecive = false
					this.socketTask = false
					this.msg = false
					console.log('onClose', res)
				})
				console.log('task', this.socketTask)
			},
			send() {
				this.socketTask.send({
					data: 'from ' + platform + ' : ' + parseInt(Math.random() * 10000).toString(),
					success(res) {
						console.log(res);
					},
					fail(err) {
						console.log(err);
					}
				})
			},
			close() {
				if (this.socketTask && this.socketTask.close) {
					this.socketTask.close()
				}
			}
		}
	}
</script>

<style>
	.uni-padding-wrap {
		width: 690rpx;
		padding: 0 30rpx;
	}

	.uni-btn-v {
		padding: 10rpx 0;
	}

	.uni-btn-v button {
		margin: 20rpx 0;
	}

	.websocket-msg {
		padding: 40px 0px;
		text-align: center;
		font-size: 14px;
		line-height: 40px;
		color: #666666;
	}

    .websocket-tips{
        padding: 40px 0px;
        text-align: center;
        font-size: 14px;
        line-height: 24px;
        color: #666666;
    }
</style>

某项业务完成
比如查询礼品库存详情时 向有webSocket 连接的页面发送消息

具体业务所在对的Service类中
 @Autowired
    private CustomerPhonePushSocket customerPhonePushSocket;

 /**
     * 查询礼品变动详情
     * @param giftChangeId
     * @return
     */
    public GiftChangeVo detail(Long giftChangeId) {
        GiftChange giftChange = this.giftChangeDao.selectById(giftChangeId);
        GiftChangeVo giftChangeVo = new GiftChangeVo();
        BeanUtils.copyProperties(giftChange,giftChangeVo);
        try {
            customerPhonePushSocket.sendMsgToAll("你查询了礼品变动详情");  // 这种事广播的形式,会向所有有建立长链接的页面发送消息
        } catch (IOException e) {
            e.printStackTrace();
        }
        return giftChangeVo;
    }

前端有建立webSocket 连接的页面就能收到 这条消息了。
就完成了消息推送。
疑问:如何通过session 来向指定打开了webSocket的页面发送消息呢?

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值