springboot+websocket后端代码实现

引入依赖

<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.1.13.RELEASE</version>
	<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-websocket</artifactId>
	<version>2.2.6.RELEASE</version>
</dependency>
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

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

import com.alibaba.fastjson.JSONObject;
import com.ndsoft.single.bizservice.repository.MessageInfoRepository;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

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


@ServerEndpoint("/webSocket/talk/{userId}/{acceptId}")
@Service
public class WebSocketService {

    private Session session;

//    private static CopyOnWriteArraySet<WebSocketService> webSocketSet = new CopyOnWriteArraySet<WebSocketService>();

    private static MessageInfoRepository messageInfoRepository;

    @Autowired
    public void setMessageInfoRepository(MessageInfoRepository messageInfoRepository) {
        WebSocketService.messageInfoRepository = messageInfoRepository;
    }

    private static Map<String, WebSocketService> userMap = new HashMap<>();

    private String acceptId;

    private String userId;

    public static RedisService redisService;

    private MessageInfo messageInfo;

    private String infoKey;

    private final static String PREFIX = "MSG";

    /**
     * 建立连接
     *
     * @Author : yyc
     * @CreateDate : 2020/8/9
     */
    @OnOpen
    public void onOpen(@PathParam(value = "userId") String userId, @PathParam(value = "acceptId") String acceptId, Session session)    	throws IOException{
    	// 连接成功 发送消息
        this.session = session;
        this.acceptId = acceptId;
        this.userId = userId;
        userMap.put(PREFIX + userId, this);
        sendBasicMesszzzage("连接成功");
    }

    
    @OnMessage
    public void onMessage(String message)throws IOException {
            WebSocketService webSocketTest = userMap.get(PREFIX + acceptId);
            if (webSocketTest != null) {
                webSocketTest.sendAsyncMessage(content);
            }
    }

    @OnClose//关闭连接执行
    public void onClose(Session session) {}

    @OnError//连接错误的时候执行
    public void onError(Throwable error, Session session) {error.printStackTrace();}


    /**
     * 异步发送消息
     *
     */
    private void sendAsyncMessage(String message) throws IOException {this.session.getAsyncRemote().sendText(message);}

    /**
     * 同步发送消息
     *
     */
    private void sendBasicMessage(String message) throws IOException {this.session.getBasicRemote().sendText(message);}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值