非JSR356 标准的WebSocket,WebLogic12.1.2下的实现方式
Error during WebSocket handshake: Unexpected response code: 404
描述:项目中需要使用websocket技术,服务端和客户端进行相互通信。一开始使用Tomcat7.0.76使用的JSR标准的WebSocket实现,使用Weblogic12.1.3发布功能没有任何问题。但在客户的WebLogic12.1.2服务器下WebSocket无法连接:Error during WebSocket handshake: Unexpected response code: 404。经调查WebLogic12.1.2及其以下不支持JSR356 标准的WebSocket。
JSR356 标准的WebSocket可以参考上篇博文:https://blog.csdn.net/weixin_36782521/article/details/110913153
以下是WebLogic12.1.2实现WebSocket的例子:
Java
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import weblogic.websocket.ClosingMessage;
import weblogic.websocket.WebSocketAdapter;
import weblogic.websocket.WebSocketConnection;
import weblogic.websocket.annotation.WebSocket;
@WebSocket(pathPatterns = {"/websocket/*"}, timeout = -1)
public class WebScoketAction extends WebSocketAdapter {
public static List<WebSocketConnection> connections = new ArrayList<WebSocketConnection>();
private WebSocketConnection connection;
@Override
public void onOpen(WebSocketConnection connection) {
System.out.println("*** WebSocket opened from sessionId " + connection.getRemoteAddress());
super.onOpen(connection);
this.connection = connection;
connections.add(this.connection);
}
@Override
public void onClose(WebSocketConnection connection, ClosingMessage msg) {
System.out.println("*** WebSocket closed from sessionId " + connection.getRemoteAddress() + ": " + msg);
super.onClose(connection, msg);
connections.remove(connection);
}
@Override
public void onMessage(WebSocketConnection connection, String payload) {
System.out.println("*** WebSocket onMessage from sessionId " + connection.getRemoteAddress() + ": " + payload);
super.onMessage(connection, payload);
}
public static void sendMessage(String msg) {
System.out.println("Send Message : " + msg);
for (WebSocketConnection connection : connections) {
if(connection.isOpen()) {
try {
connection.send(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test WebSocket</title>
<script type="text/javascript">
// http://localhost:8080/TestWebSocket
var ws = null;
function startWebSocket() {
if ('WebSocket' in window) {
ws = new WebSocket("ws://localhost:8080/TestWebSocket/websocket/li");
} else {
alert("not support");
}
ws.onmessage = function(evt) {
//接收到消息
alert(evt.data);
};
ws.onclose = function(evt) {
alert("close");
// 异常关闭重新连接
startWebSocket();
};
ws.onopen = function(evt) {
alert("open");
};
}
function sendMsg() {
ws.send(document.getElementById('writeMsg').value);
}
</script>
</head>
<body onload="startWebSocket();">
<input type="text" id="writeMsg"></input>
<input type="button" value="send" onclick="sendMsg()"></input>
</body>
</html>