Java搭建WebSocket的两种方式 (5)

                    attributes.put("WEBSOCKET_USERID", userName);//放入attributes中,可以在处理器的WebSocketSession中取出

                }

            }

        }

        return super.beforeHandshake(request, response, wsHandler, attributes);

    }

    @Override

    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,

                               Exception ex) {

        super.afterHandshake(request, response, wsHandler, ex);

        System.out.println("after Handshake");

    }

}

参考:

https://my.oschina.net/u/3445245/blog/3003208

https://blog.csdn.net/runbat/article/details/80985944

https://docs.spring.io/spring/docs/5.0.0.BUILD-SNAPSHOT/spring-framework-reference/html/websocket.html

下面分别介绍websocket的java客户端请求和js客户端请求

1、java客户端

添加依赖:

<dependency>

<groupId>org.java-websocket</groupId>

<artifactId>Java-WebSocket</artifactId>

<version>1.4.0</version>

</dependency>

package com.river.websocket;

import org.java_websocket.enums.ReadyState;

import java.net.URISyntaxException;

/**

* @author river

* @date 2019-12-6

*/

public class Client {

public static void main(String[] args) throws URISyntaxException, InterruptedException {

MyWebSocketClient client = new MyWebSocketClient("ws://localhost:8080/websocket/server");

client.connect();

while (client.getReadyState() != ReadyState.OPEN) {

System.out.println("连接状态:" + client.getReadyState());

Thread.sleep(100);

}

client.send("测试数据!");

client.close();

}

}

继承WebsocketClient

package com.river.websocket;

import org.java_websocket.client.WebSocketClient;

import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;

import java.net.URISyntaxException;

public class MyWebSocketClient extends WebSocketClient {

MyWebSocketClient(String url) throws URISyntaxException {

super(new URI(url));

}

@Override

public void onOpen(ServerHandshake shake) {

System.out.println(shake.getHttpStatusMessage());

}

@Override

public void onMessage(String paramString) {

System.out.println(paramString);

}

@Override

public void onClose(int paramInt, String paramString, boolean paramBoolean) {

System.out.println("关闭");

}

@Override

public void onError(Exception e) {

System.out.println("发生错误");

}

}

2、js客户端

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

<title>websocket</title>

<script type="text/javascript" src="http://cdn.bootcss.com/jquery/3.1.0/jquery.min.js"></script>

<script type="text/javascript" src="http://cdn.bootcss.com/sockjs-client/1.1.1/sockjs.js"></script>

<script type="text/javascript">

var websocket = null;

if (\'WebSocket\' in window) {

websocket = new WebSocket("ws://localhost:8080/websocket/server");

} else if (\'MozWebSocket\' in window) {

websocket = new MozWebSocket("ws://localhost:8080/websocket/server");

} else {

websocket = new SockJS("http://localhost:8080/sockjs/server");

}

websocket.onopen = onOpen;

websocket.onmessage = onMessage;

websocket.onerror = onError;

websocket.onclose = onClose;

function onOpen(event) {

alert(event.type);

}

function onMessage(messageEvent) {

alert(messageEvent.data);

}

function onError(event) {

}

function onClose(closeEvent) {

alert(closeEvent.reason);

}

function doSendUser() {

if (websocket.readyState === websocket.OPEN) {

var msg = document.getElementById("inputMsg").value;

websocket.send(msg);//发送消息

alert("发送成功!");

} else {

alert("连接失败!");

}

}

window.close = function () {

websocket.onclose();

};

function websocketClose() {

websocket.close();

alert("连接关闭");

}

</script>

</head>

<body>

请输入:<input/>

<button οnclick="doSendUser();">发送</button>

<button οnclick="websocketClose();">关闭连接</button>

</body>

</html>

补充:登录方式除了在Controller中处理,还可以在Websocket中接收到的消息进行登录处理。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwxjzf.html