技术简介:Springboot2.0.3+freemaker+websocket

1、添加pom依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

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

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-freemarker</artifactId>
    </dependency>

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.3</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
    </dependency>

    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.4</version>
    </dependency>

</dependencies>

2、添加配置文件application.yml

server:
  servlet:
   context-path: /mujiutian
spring:
  freemarker:
    allow-request-override: false
    cache: true
    check-template-location: true
    charset: UTF-8
    content-type: text/html
    expose-request-attributes: false
    expose-session-attributes: false
    expose-spring-macro-helpers: false
    suffix: .html
  profiles:
    active: dev

3、创建IM.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>websocket通讯</title>
</head>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
    var socket;
    function openSocket() {
        if(typeof(WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
        }else{
            console.log("您的浏览器支持WebSocket");

            var socketUrl="http://localhost:8080/mujiutian/im/"+$("#userId").val();
            socketUrl=socketUrl.replace("https","ws").replace("http","ws");
            console.log(socketUrl)
            socket = new WebSocket(socketUrl);
            //打开事件
            socket.onopen = function() {
                console.log("websocket已打开");
                //socket.send("这是来自客户端的消息" + location.href + new Date());
            };
            //获得消息事件
            socket.onmessage = function(msg) {
                console.log(msg.data);
                //发现消息进入    开始处理前端触发逻辑
            };
            //关闭事件
            socket.onclose = function() {
                console.log("websocket已关闭");
            };
            //发生了错误事件
            socket.onerror = function() {
                console.log("websocket发生了错误");
            }
        }
    }
    function sendMessage() {
        if(typeof(WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
        }else {
            console.log("您的浏览器支持WebSocket");
            console.log('[{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}]');
            socket.send('[{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}]');
        }
    }
</script>
<body>
<p>【userId】:<input id="userId" name="userId" type="text">
<p>【toUserId】:<input id="toUserId" name="toUserId" type="text">
<p> [发送内容]:<input id="contentText" name="contentText" type="text" maxlength="50">
<input type="button" οnclick="openSocket()" value="开启socket" style="background: cyan;background-color: red;width: auto;height: auto;"/>
<input type="button" οnclick="sendMessage()" value="发送消息" style="background: cyan;background-color: lightgrey;width: auto;height: auto;" />
</body>

</html>

4、配置类

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

/**
 * @Author:Mujiutian
 * @Description:
 * @Date: Created in 上午11:15 2018/12/13
 */
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}

5、Component类

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;

/**
 * @Author:Mujiutian
 * @Description:
 * @Date: Created in 上午11:16 2018/12/13
 */
@ServerEndpoint(value = "/websocket/{sid}")
@Component
public class WebSocketServer {

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

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

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

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

    //接收sid
    private String sid = "";

    /**
     *
     * @Description:连接建立成功调用的方法
     * @Date:2018/12/13 下午3:16
     * @Author:Mujiutian
     * @UpdateRemark:
     * @Version:1.0
     *
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("sid")String sid) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        log.info("有新窗口开始监听:"+sid+"有新连接加入!当前在线人数为" + getOnlineCount());
        this.sid = sid;

        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            log.error("websocket IO异常");
        }
    }

    /**
     *
     * @Description:连接关闭调用的方法
     * @Date:2018/12/13 下午3:15
     * @Author:Mujiutian
     * @UpdateRemark:
     * @Version:1.0
     *
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
    }

    /**
     *
     * @Description:收到客户端消息后调用的方法,message:客户端发送过来的消息
     * @Date:2018/12/13 下午3:16
     * @Author:ChengJian
     * @UpdateRemark:
     * @Version:1.0
     *
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("来自客户端的消息:" + 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();
    }


    /**
     *
     * @Description:实现服务器主动推送
     * @Date:2018/12/13 下午3:17
     * @Author:ChengJian
     * @UpdateRemark:
     * @Version:1.0
     *
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     *
     * @Description:群发自定义消息
     * @Date:2018/12/13 下午3:18
     * @Author:Mujiutian
     * @UpdateRemark:
     * @Version:1.0
     *
     */
    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--;
    }
}

6、Controller层

import com.mjt.websocket.component.WebSocketServer;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author:Mujiutian
 * @Description:
 * @Date: Created in 上午11:33 2018/12/13
 */
@Controller
public class HelloWorldController {

    @RequestMapping(value = "/IM.html/{userId}")
    public String IM(ModelMap modelMap,@PathVariable String userId){
        modelMap.put("userId",userId);
        return "IM";
    }

    @RequestMapping(value="/pushListToWeb")
    @ResponseBody
    public Map<String,Object> pushVideoListToWeb(String cid,String message) {
        Map<String,Object> result =new HashMap<>();

        try {
            WebSocketServer.sendInfo(message,cid);
            result.put("operationResult", true);
        }catch (IOException e) {
            result.put("operationResult", true);
        }
        return result;
    }
}

7、测试

7.1 调用现实页面 http://localhost:8080/mujiutian/IM.html/20

崛起于Springboot2.X之通讯WebSocket(40)

然后开启socket,如下

崛起于Springboot2.X之通讯WebSocket(40)

之后结果为:

崛起于Springboot2.X之通讯WebSocket(40)

崛起于Springboot2.X之通讯WebSocket(40)

然后同上操作换一个userId为114,结果为:

崛起于Springboot2.X之通讯WebSocket(40)

7.2 然后给发送人发送消息,如下

崛起于Springboot2.X之通讯WebSocket(40)

结果为:

崛起于Springboot2.X之通讯WebSocket(40)

那么我们通讯完成,具体逻辑业务在IMSocketServer中处理就好

转载于:https://my.oschina.net/mdxlcj/blog/2988194

相关文章: