SpringBoot+WebSocket

     了解一个知识你得知道他是什么,有什么用,怎么用。所以我们从这三个方面入手

 

  WebSocket是什么?

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

 

  WebSocket有什么用?

     既然有了http协议为什么还需要其他协议呢?有什么好处吗?

     因为http协议有缺陷就是通讯不能由服务器发起,只能由客户端发起。最典型的场景就是聊天室,如果用http协议的话只能用轮询的方式去获取消息,这种方式又很耗费资源。这时候WebSocket就应运而生了,WebSocket实现了可以由服务端主动发送消息给客服端的需求

 

   WebSocket怎么用?

      话不多说上代码

   1.添加maven依赖

        <!--webSocket-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

 

 2.编写WebSocketConfig配置类

     

package cn.com.citydo.gatherdata.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * @Descritpion 开启WebSocket支持
 * @Author: ZJH940925
 * @Date: 15:57
 */
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

 

  3.编写WebSocketServer

package cn.com.citydo.sjpc_gatherdata.service.impl;

import cn.com.citydo.sjpc_gatherdata.config.WebSocketEncoder;
import cn.com.citydo.sjpc_gatherdata.entity.SocketMessage;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Descritpion WebSocket服务
 * @Author: ZJH940925
 * @Date: 16:00
 */
@Component
@ServerEndpoint(value = "/websocket",encoders = {WebSocketEncoder.class})
public class WebSocketServer {
    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;
    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        try {
        	 sendMessage("连接成功");
        } catch (IOException e) {
        } catch (EncodeException e) {
            e.printStackTrace();
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        System.out.println("关闭连接");
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
    	System.out.println("收到来自窗口的信息:"+message);
        //群发消息
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (EncodeException e) {
                e.printStackTrace();
            }
        }
    }

	/**
	 * 
	 * @param session
	 * @param error
	 */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }
	/**
	 * 实现服务器主动推送
	 */
    public void sendMessage(String message) throws IOException, EncodeException {
        this.session.getBasicRemote().sendText(message);
    }
    /**
	 * 实现服务器主动推送实体类
	 */
    public void sendObject(Object message) throws IOException, EncodeException {
        this.session.getBasicRemote().sendObject(message);
    }


    /**
     * 群发自定义消息 消息为对象
     * */
    public static void sendInfo(SocketMessage message) throws IOException {
    	System.out.println("推送消息到窗口,推送内容:"+message);
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendObject(message);
            } catch (IOException e) {
                continue;
            } catch (EncodeException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 群发自定义消息
     * */
    public static void sendInfo(String message) throws IOException {
        System.out.println("推送消息到窗口,推送内容:"+message);
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            } catch (EncodeException e) {
                e.printStackTrace();
            }
        }
    }
}



  4.编写WebSocketController

package cn.com.citydo.gatherdata.Controller;

import cn.com.citydo.gatherdata.service.impl.WebSocketServer;
import com.citydo.comm.httpmodel.HttpResultModel;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;

/**
 * @Descritpion
 * @Author: ZJH940925
 * @Date: 17:46
 */
@RestController
@RequestMapping("/webSocket")
public class WebSocketController {

  
	//发送数据给前端
	@ResponseBody
	@RequestMapping("/socket/push")
	public HttpResultModel pushToWeb() {
		try {
			WebSocketServer.sendInfo("我是测试数据");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return HttpResultModel.success();
	}

}

5.编写编译器(可以把消息封装到实体类 按照类进行发送)

package cn.com.citydo.sjpc_gatherdata.config;

import cn.com.citydo.sjpc_gatherdata.entity.SocketMessage;
import com.alibaba.fastjson.JSON;

import javax.websocket.EncodeException;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;


/**
 * @Descritpion webSocket传输对象时候的编译器
 * @Author: ZJH940925
 * @Date: 18:04
 */
public class WebSocketEncoder implements Encoder.Text<SocketMessage> {
    @Override
    public String encode(SocketMessage socketMessage) throws EncodeException {
            return   JSON.toJSONString(socketMessage);
    }

    @Override
    public void init(EndpointConfig endpointConfig) {

    }

    @Override
    public void destroy() {

    }
}

  

6.编写test.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
</head>

<script>
    var socket;
    if(typeof(WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
    }else{
        console.log("您的浏览器支持WebSocket");
        // console.log("${basePath}demosocket/${cid}".replace("http","ws"));
        //实现化WebSocket对象,指定要连接的服务器地址与端口  建立连接
        //等同于socket = new WebSocket("ws://localhost:8083/checkcentersys/websocket/20");
        socket = new WebSocket("ws://localhost:8092/websocket");
        //打开事件
        socket.onopen = function() {
            console.log("Socket 已打开");
            //socket.send("这是来自客户端的消息" + location.href + new Date());
        };
        //获得消息事件
        socket.onmessage = function(msg) {
            console.log(msg.data);
            //发现消息进入    开始处理前端触发逻辑
        };
        //关闭事件
        socket.onclose = function() {
            console.log("Socket已关闭");
        };
        //发生了错误事件
        socket.onerror = function() {
            alert("Socket发生了错误");
            //此时可以尝试刷新页面
        }
        //离开页面时,关闭socket
        //jquery1.8中已经被废弃,3.0中已经移除
        // $(window).unload(function(){
        //     socket.close();
        //});
    }
</script>

<body>
hi !!!
</body>
</html>

5.测试

                    

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值