WebSocket集成

前端:

React-ant-design

import React, { Component } from 'react';
import { Input, Button } from 'antd';
import 'antd/dist/antd.css';
import './index.css';
class index extends Component {
  state = {
    userId: '1',
    contentText: '这是信息',
    toUserId: '2',
    socket: ''
  };
  onChangeUserId = e => {
    this.setState({
      userId: e.target.value,
    });
  };
  onChangeToUserId = e => {
    this.setState({
      toUserId: e.target.value,
    });
  };
  onChangeContentText = e => {
    this.setState({
      contentText: e.target.value,
    });
  };
  openSocket = () => {
    if (typeof (WebSocket) == "undefined") {
      console.log("您的浏览器不支持WebSocket");
    } else {
      console.log("您的浏览器支持WebSocket");
      //实现化WebSocket对象,指定要连接的服务器地址与端口  建立连接
      //等同于socket = new WebSocket("ws://localhost:8080/xxxx/im/25");
      //var socketUrl="${request.contextPath}/im/"+$("#userId").val();
      // var socketUrl = "http://localhost:8080/websocket/" + $("#userId").val();
      var socketUrl = "http://localhost:8080/websocket/" + this.state.userId;
      console.log(socketUrl)
      socketUrl = socketUrl.replace("https", "ws").replace("http", "ws");
      console.log(socketUrl)
      this.state.socket = new WebSocket(socketUrl);
      //打开事件
      this.state.socket.onopen = function () {
        console.log("websocket已打开");
        //socket.send("这是来自客户端的消息" + location.href + new Date());
      };
      //获得消息事件
      this.state.socket.onmessage = function (msg) {
        console.log(msg.data);
        //发现消息进入    开始处理前端触发逻辑
      };
      //关闭事件
      this.state.socket.onclose = function () {
        console.log("websocket已关闭");
      };
      //发生了错误事件
      this.state.socket.onerror = function () {
        console.log("websocket发生了错误");
      }
    }
  };
  sendMessage = () => {
    if (typeof (WebSocket) == "undefined") {
      console.log("您的浏览器不支持WebSocket");
    } else {
      console.log("您的浏览器支持WebSocket");
      console.log('[{"toUserId":"' + this.state.toUserId + '","contentText":"' + this.state.contentText);
      this.state.socket.send('[{"toUserId":"' + this.state.toUserId + '","contentText":"' + this.state.contentText);
    }
  }
  render() {
    return (
    
     <div>
        【userId】:<Input placeholder="input with clear icon" allowClear name='userid' onChange={this.onChangeUserId} value={this.state.userId} />
        【toUserId】:<Input placeholder="input with clear icon" allowClear name='toUserId' onChange={this.onChangeToUserId} value={this.state.toUserId} />
        【contentText】:<Input placeholder="input with clear icon" allowClear name='contentText' onChange={this.onChangeContentText} value={this.state.contentText} />
        【操作】:<Button type="primary" onClick={this.openSocket}>开启socket
        </Button>
        【操作】:<Button type="primary" onClick={this.sendMessage}>发送消息
        </Button>
      </div>   );
      }
      }export default index;

JS:

<!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");
            //实现化WebSocket对象,指定要连接的服务器地址与端口  建立连接
            //等同于socket = new WebSocket("ws://localhost:8080/xxxx/im/25");
            //var socketUrl="${request.contextPath}/im/"+$("#userId").val();
            var socketUrl="http://localhost:8080/websocket/"+$("#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】:<div><input id="userId" name="userId" type="text" value="1"></div>
    <p>【toUserId】:<div><input id="toUserId" name="toUserId" type="text" value="2"></div>
    <p>【toUserId】:<div><input id="contentText" name="contentText" type="text" value="这是信息"></div>
    <p>【操作】:<div><a onclick="openSocket()">开启socket</a></div>
    <p>【操作】:<div><a onclick="sendMessage()">发送消息</a></div>
</body>

</html>

后台

spring-boot:
依赖:

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

WebSocketConfig:

package com.wu.parker.websocket.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();
    }
}

Controller

package com.wu.parker.websocket.controller;

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.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: wusq
 * @date: 2018/12/10
 */
@ServerEndpoint("/websocket/{token}")
@Component
public class WebSocketController {

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

    public static Map<String, Session> SESSION_MAP = new ConcurrentHashMap<>();

    /**
     * 连接建立成功调用的方法
     * @param session
     * @param token
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) {
        log.info("{}建立连接", token);
        SESSION_MAP.put(token, session);
        log.info("建立连接后session数量={}", SESSION_MAP.size());
        send(token, "Hello, connection opened!");
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        for(Map.Entry<String, Session> entry:SESSION_MAP.entrySet()){
            log.info("session.id={}", session.getId());
            if(session.getId().equals(entry.getValue().getId())){
                log.info("{}发来消息", entry.getKey());
            }
            break;
        }
        log.info("接收到消息:{}", message);

    }

    @OnClose
    public void onClose(Session session) {
        log.info("有连接关闭");
        Map<String, Session> map = new HashMap<>();
        SESSION_MAP.forEach((k, v) -> {
            if(!session.getId().equals(v.getId())){
                map.put(k, v);
            }
        });
        SESSION_MAP = map;
        log.info("断开连接后session数量={}", SESSION_MAP.size());
    }

    void send(String token, String message){
        Session session = SESSION_MAP.get(token);
        if(session != null){
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                log.error("发送信息错误{}", e.getMessage());
                e.printStackTrace();
            }
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

}

参考地址:
https://blog.csdn.net/wu_boy/article/details/84944981

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值