websocketService,WebSocketClient笔记

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.springframework.web.socket.server.standard.SpringConfigurator;

/**
 * @ServerEndpoint socket客户端的连接地址 eg:127.0.0.1:8080/websocket
 */
@ServerEndpoint(value = "/websocket", configurator = SpringConfigurator.class)
public class WebSocketService {
    // 统计在线数量,测试作用
    private static int onlineCount = 0;

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

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

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        // 新连接加入set中
        webSocketSet.add(this);
        // 在线数加1
        onlineCount++;
        System.out.println("有新连接加入!当前在线人数为" + onlineCount);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        // 从set中删除
        webSocketSet.remove(this);
        // 在线数减1
        onlineCount--;
        System.out.println("有一连接关闭!当前在线人数为" + onlineCount);
    }

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

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        // 可以写入日志
        System.out.println("------ onError ------");
    }

    // 推送消息
    private void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 主动推送消息,可以供外部调用
     * 
     * WebSocketService webSocketService = new WebSocketService();
     * webSocketService.sendMsg("message");
     */
    public void sendMsg(String msg) {
        for (WebSocketService item : webSocketSet) {
            try {
                item.sendMessage(msg);
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }
    }
}

--------------------------------------------------------------------------------------------------------------

import java.net.URI;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.xyp.entity.TencentMessage;
import com.xyp.service.IUserService;

/**
 ** 消息处理统一入口
 */
@Component
public class MsgWebSocketClient extends WebSocketClient {
    // 发送消息
    private static MsgWebSocketClient socketClient = null;
    private static URI uriInstance = null;

    public MsgWebSocketClient(URI uriInstance) {
        super(uriInstance);
    }

    @Autowired
    void setUriInstance(URI uri) {
        uriInstance = uri;
    }
    // 注入userService
    private static IUserService userService;

    @Autowired
    void setUserService(IUserService userService) {
        MsgWebSocketClient.userService = userService;
    }

    @Override
    public void onMessage(String msg) {
        System.out.println(JSONObject.parseObject(msg, TencentMessage.class));
    }

    public static void init() {
        if (socketClient == null) {
            socketClient = new MsgWebSocketClient(uriInstance);
        }
        socketClient.connect();
    }

    @Override
    public void onOpen(ServerHandshake arg0) {
        System.out.println("------ MyWebSocket onOpen ------");
    }

    @Override
    public void onClose(int arg0, String arg1, boolean arg2) {
        System.out.println("------ MyWebSocket onClose ------");
    }

    @Override
    public void onError(Exception arg0) {
        System.out.println("------ MyWebSocket onError ------");
    }
}

 

socket相关的pom

        <dependency>
            <groupId>org.java-websocket</groupId>
            <artifactId>Java-WebSocket</artifactId>
            <version>1.4.0</version>
        </dependency>

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值