天天看点

java socket 服务器推送_websocket实现服务器向客户端推送消息

WebSocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器全双工(full-duplex)通信——允许服务器主动发送信息给客户端。

java socket 服务器推送_websocket实现服务器向客户端推送消息

image.png

1、新建SpringBoot项目

java socket 服务器推送_websocket实现服务器向客户端推送消息

image.png

2、pom.xml依赖

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

org.springframework.boot

spring-boot-starter-parent

2.2.1.RELEASE

com.wzf

websocket

0.0.1-SNAPSHOT

websocket

Demo project for Spring Boot

1.8

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-websocket

2.2.1.RELEASE

org.projectlombok

lombok

true

org.springframework.boot

spring-boot-starter-test

test

org.junit.vintage

junit-vintage-engine

org.springframework.boot

spring-boot-maven-plugin

3、WebSocketConfig.java

启用WebSocket的支持也是很简单,几句代码搞定

package com.wzf.websocket;

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();

}

}

4、WebSocketServer.java

因为WebSocket是类似客户端服务端的形式(采用ws协议),那么这里的WebSocketServer其实就相当于一个ws协议的Controller,直接@ServerEndpoint("/websocket"),@Component启用即可,然后在里面实现@OnOpen,@onClose,@onMessage等方法

package com.wzf.websocket;

import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Component;

import javax.websocket.*;

import javax.websocket.server.PathParam;

import javax.websocket.server.ServerEndpoint;

import java.io.IOException;

import java.util.concurrent.CopyOnWriteArraySet;

@Slf4j

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

@Component

public class WebSocketServer {

//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。

private static int onlineCount = 0;

//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。

private static CopyOnWriteArraySet webSocketSet = new CopyOnWriteArraySet();

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

private Session session;

//接收sid

private String sid="";

@OnOpen

public void onOpen(Session session,@PathParam("sid") String sid) throws InterruptedException {

this.session = session;

webSocketSet.add(this); //加入set中

addOnlineCount(); //在线数加1

log.info("有新窗口开始监听:"+sid+",当前在线人数为" + getOnlineCount());

this.sid=sid;

try {

//模拟服务器向客户端发消息(群发)

sendMessage("连接成功");

//模拟服务器向客户端发消息(某一20客户端)

for(int i = 0; i<5; i++){

Thread.sleep(1000);

sendInfo(String.valueOf(i), "20");

}

} catch (IOException e) {

log.error("websocket IO异常");

}

}

@OnClose

public void onClose() {

webSocketSet.remove(this); //从set中删除

subOnlineCount(); //在线数减1

log.info("有一连接关闭!当前在线人数为" + getOnlineCount());

}

@OnMessage

public void onMessage(String message, Session session) {

log.info("收到来自窗口"+sid+"的信息:"+message);

//群发消息

for (WebSocketServer item : webSocketSet) {

try {

item.sendMessage(message);

} catch (IOException e) {

e.printStackTrace();

}

}

}

@OnError

public void onError(Session session, Throwable error) {

log.error("发生错误");

// error.printStackTrace();

}

public void sendMessage(String message) throws IOException {

this.session.getBasicRemote().sendText(message);

}

public static void sendInfo(String message,@PathParam("sid") String sid) throws IOException {

log.info("推送消息到窗口"+sid+",推送内容:"+message);

for (WebSocketServer item : webSocketSet) {

try {

//这里可以设定只推送给这个sid的,为null则全部推送

if(sid==null) {

item.sendMessage(message);

}else if(item.sid.equals(sid)){

item.sendMessage(message);

}

} catch (IOException e) {

continue;

}

}

}

public static synchronized int getOnlineCount() {

return onlineCount;

}

public static synchronized void addOnlineCount() {

WebSocketServer.onlineCount++;

}

public static synchronized void subOnlineCount() {

WebSocketServer.onlineCount--;

}

}

5、客户端 test1.html (sid=20)

var socket;

if(typeof(WebSocket) == "undefined") {

console.log("您的浏览器不支持WebSocket");

}else{

console.log("您的浏览器支持WebSocket");

//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接

socket = new WebSocket("ws://localhost:8080/websocket/20");

//打开事件

socket.onopen = function() {

console.log("Socket 已打开");

//socket.send("这是来自客户端的消息" + location.href + new Date());

};

//获得消息事件

socket.onmessage = function(msg) {

console.log(msg.data);

//发现消息进入 开始处理前端触发逻辑

let msgDiv = document.getElementById("messageId");

msgDiv.innerHTML = msg.data;

};

//关闭事件

socket.onclose = function() {

console.log("Socket已关闭");

};

//发生了错误事件

socket.onerror = function() {

alert("Socket发生了错误");

//此时可以尝试刷新页面

}

}

6、客户端 test2.html (sid=30)

var socket;

if(typeof(WebSocket) == "undefined") {

console.log("您的浏览器不支持WebSocket");

}else{

console.log("您的浏览器支持WebSocket");

//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接

socket = new WebSocket("ws://localhost:8080/websocket/30");

//打开事件

socket.onopen = function() {

console.log("Socket 已打开");

//socket.send("这是来自客户端的消息" + location.href + new Date());

};

//获得消息事件

socket.onmessage = function(msg) {

console.log(msg.data);

//发现消息进入 开始处理前端触发逻辑

let msgDiv = document.getElementById("messageId");

msgDiv.innerHTML = msg.data;

};

//关闭事件

socket.onclose = function() {

console.log("Socket已关闭");

};

//发生了错误事件

socket.onerror = function() {

alert("Socket发生了错误");

//此时可以尝试刷新页面

}

}

7、启动SpringBoot程序,然后分别在两个不同的窗口中打开test1.html和test2.html页面。效果如下:

java socket 服务器推送_websocket实现服务器向客户端推送消息

image.png

java socket 服务器推送_websocket实现服务器向客户端推送消息

image.png

java socket 服务器推送_websocket实现服务器向客户端推送消息

image.png