webSocket 和java 实现互发信息

webSocket.js

class MyWebSocket extends WebSocket {
    constructor(params) {
        const urlPrefix = 'ws://' + window.location.host + '/chat-room/';
        const url = urlPrefix + params.name;
        super(url);
        this.name = params.name;

        //批量添加webSocket函数
        const keys = Object.getOwnPropertyNames(params).filter(param => typeof params[param] == "function");
        keys.map(key => {
            this[key] = params[key];
            console.log(params[key])
        })
    }

    send1(receive, info) {
        $.get("/chat-room/" + this.name + "/to/" + receive + "?message=" + info, function () {
            console.log("发送成功:" + info)
        })
    }
}

调用




function(){
//群发信息
socket.send("2222")
}

function(){
//私发信息
  socket.send1("2222",a);
}

java部分
参考来源
POM.XML


    
        org.springframework.boot
        spring-boot-starter-web
    
    
        org.springframework.boot
        spring-boot-starter-websocket
    

socket.java

package com.xzff.frame.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

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

import static com.xzff.frame.webSocket.WebSocketUtils.LIVING_SESSIONS_CACHE;
import static com.xzff.frame.webSocket.WebSocketUtils.sendMessage;
import static com.xzff.frame.webSocket.WebSocketUtils.sendMessageAll;

@Controller
@ResponseBody
@ServerEndpoint("/chat-room/{username}")
public class socket {
    private static final Logger log = LoggerFactory.getLogger(socket.class);

    @OnOpen
    public void openSession(@PathParam("username") String username, Session session) {
        LIVING_SESSIONS_CACHE.put(username, session);
        String message = "欢迎用户[" + username + "] 来到聊天室!";
        log.info(message);
        sendMessageAll(message);
    }

    @OnMessage
    public void onMessage(@PathParam("username") String username, String message) {
        log.info(message);
        sendMessageAll("用户[" + username + "] : " + message);
    }

    @OnClose
    public void onClose(@PathParam("username") String username, Session session) {
        //当前的Session 移除
        LIVING_SESSIONS_CACHE.remove(username);
        //并且通知其他人当前用户已经离开聊天室了
        sendMessageAll("用户[" + username + "] 已经离开聊天室了!");
        try {
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        try {
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        throwable.printStackTrace();
    }


    @RequestMapping("/chat-room/{sender}/to/{receive}")
    public void onMessage(@PathVariable("sender") String sender, @PathVariable("receive") String receive, String message) {
        sendMessage(LIVING_SESSIONS_CACHE.get(receive),message);
    }
}

WebSocketUtils.java

package com.xzff.frame.webSocket;

import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public final class WebSocketUtils {
    /**
     * 模拟存储 websocket session 使用
     */
    public static final Map LIVING_SESSIONS_CACHE = new ConcurrentHashMap<>();

    public static void sendMessageAll(String message) {
        LIVING_SESSIONS_CACHE.forEach((sessionId, session) -> sendMessage(session, message));
    }

    /**
     * 发送给指定用户消息
     *
     * @param session 用户 session
     * @param message 发送内容
     */
    public static void sendMessage(Session session, String message) {
        if (session == null) {
            return;
        }
        final RemoteEndpoint.Basic basic = session.getBasicRemote();
        if (basic == null) {
            return;
        }
        try {
            basic.sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(java)