【Spring Boot】Spring Boot启用WebSocket实现用户与用户间发送消息

Spring Boot使用WebSocket实现用户之间发送消息

步骤

1.在pom中添加websocket依赖

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

2.向容器添加ServerEndpointExporter组件

@Configuration
public class WebSocketConfig{

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

3.配置服务器端点类

注解**@ServerEndpoint**标记一个服务器端点类,用来响应和处理用户发送的消息。参数为客户端连接WebSocket需要的地址。其中可以用占位符传递参数,用法类似Controller中的路径变量。

@Service
//sessionId指定当前连接的用户将要给其他哪个用户发消息
@ServerEndpoint("/s/{sessionId}")
public class WebSocketServiceImpl{

    private static ConcurrentHashMap<String, Session> map = new ConcurrentHashMap<>();

    //建立连接
    @OnOpen
    public void onOpen(Session session){
        System.out.println("onOpen()" + session.getId());
        map.put(session.getId(),session);
    }

    //关闭连接
    @OnClose
    public void onClose(Session session){
        System.out.println("onClose()" + session.getId());
        map.remove(session.getId());
    }

    //服务端收到客户端发送的消息
    @OnMessage
    public void onMessage(@PathParam("sessionId")String sessionId , String message, Session session) throws IOException{
        System.out.println("onMessage(),用户发送的信息为:" + message + ",sessionId=" + session.getId());
        //发送给sessionId为2的用户
        Session target=map.get(String.valueOf(sessionId));
        if(target!=null){
			//同步发送
            target.getBasicRemote().sendText(message+"\n");
			//异步发送
			//target.getAsyncRemote().sendText(message+"\n");
        }
    }

    //服务端产生错误
    @OnError
    public void onError(Throwable error){
        System.out.println("onError(),message=" + error.getMessage());
    }

}

服务器端到此配置完毕,接下来配置客户端。

4.配置客户端

用户发送消息页面

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Title</title>
</head>
<body>
<h1>消息</h1>
<p id="text"></p>
<hr>
<input id="sessionId" placeholder="输入要发送用户的SessionId">
<button onclick="initWebSocket()">建立连接</button>
<input id="message" type="text" placeholder="输入要发送的消息">
<button onclick="sendMessage()">发送消息</button>
<button onclick="closeWebsocket()">关闭连接</button>
</body>
<script>
	var webSocket;
	var text=document.getElementById("text");
	
	function initWebSocket() {
	    var sessionId=document.getElementById("sessionId").value;
	    //判断浏览器是否支持WebSocket
        if("WebSocket" in window){
			//注意这里如果是https的话,协议要改成wss而不是ws
            webSocket=new WebSocket("ws://localhost:443/s/"+sessionId);
        }
        else {
            alert("不支持WebSocket!");
        }
        //连接服务器端点成功后的回调
        webSocket.onopen=function () {
            showMessage("连接成功")
        };
        webSocket.onclose=function () {
            showMessage("关闭连接");
        };
        //收到服务器端点发送来的消息后的回调
        webSocket.onmessage=function (message) {
            showMessage(message.data);
        };
        webSocket.onerror=function () {
            showMessage("连接出错");
        };
    }
    function sendMessage() {
        var msg=document.getElementById("message").value;
        //向服务器端点发送消息
		webSocket.send(msg);
    }
    function closeWebsocket() {
	    //关闭与服务器端点的连接
		webSocket.close();
    }
	function showMessage(message) {
        text.innerText+=(message);
    }
</script>
</html>

注意:
如果网站用的是http,那么连接服务器端点的url为

"ws://localhost:443/s/"

如果网站用的是https,需要将ws改为wss

"wss://localhost:443/s/"
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值