通过一个简单的示例(EchoServer应用)来了解Java WebSocket原理。这是一个客户端/服务器应用,客户端是Web浏览器上的一小段JavaScript,服务器是一个WebSocket端点。
运行环境:Java 8 ,Eclipse Java EE ,Tomcat 9.0。
创建WebSocket端点
import javax.websocket.OnMessage;
import javax.websocket.server.ServerEndpoint;
/**
* EchoServer类实现了服务器端点所拥有的功能(所有逻辑)
* @author seeker
*
*/
@ServerEndpoint(value = "/echo")
public class EchoServer {
// echo方法参数用来保存客户端发送的任意入站消息,并对它处理后返回。
@OnMessage
public String echo(String incomingMessage) {
return "I got this " + incomingMessage + "so I am sending it back.";
}
}
- @ServerEndPoint:类级别的注解,用于告诉Java平台所注解的类要成为一个WebSocket端点。唯一强制参数value是相对URI,定义了端点将被发布的路径。
- @OnMessage:方法级别的注解,用于在特定事件发生时调用方法。
创建WebSocket客户端
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Web Socket JavaScript Echo Client</title>
<script type="text/javascript" src="/socket/js/jQuery.js"></script>
<script language="javascript" type="text/javascript">
var echo_websocket;
function init() {
output = document.getElementById("output");
}
function send_echo() {
//服务器端实现功能的方法的访问路径
var wsUri = "ws://localhost:8080/socket/echo";
writeToScreen("Connection to " + wsUri);
echo_websocket = new WebSocket(wsUri);
echo_websocket.onopen = function(event) {
writeToScreen("Connected !");
doSend(textId.value);
};
echo_websocket.onmessage = function(event) {
writeToScreen("Received message:" + event.data);
echo_websocket.close();
};
echo_websocket.onerror = function(event) {
writeToScreen('<span style="color: red;"> ERROR:</span> '
+ event.data);
echo_websocket.close();
};
function doSend(message) {
echo_websocket.send(message);
writeToScreen("Send message: " + message);
}
function writeToScreen(message) {
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
window.addEventListener("load", init, false);
}
}
</script>
</head>
<body>
<h1>Echo Server</h1>
<div style="text-align: left;">
<form action="">
<input onclick="send_echo()" value="Press to send" type="button">
<input id="textId" name="message" value="Hello Web Sockets"
type="text"> <br>
</form>
</div>
<div id="output"></div>
</body>
</html>
运行结果如下: