1.引入jar包
<dependencies>
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax/javaee-api -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.websocket/javax.websocket-api -->
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
服务器使用的是Tomcat7,它自带了websocket-api.jar,所以在pom.xml中的javax.websocket-api使用了scope=provided,方便调试。
2.编写服务端代码
package cn.net.bysoft.websocketapp.lesson1;
import javax.websocket.OnMessage;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/echo")
public class EchoServer {
@OnMessage
public String echo(String incomingMessage) {
return "I got this (" + incomingMessage + ") so I am sending it back !";
}
}
服务端代码是简单的POJO,加入了两个注解,@ServerEndpoint声明了Socket端点,@OnMessage声明了消息处理函数。
3.编写客户端代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Web Socket JavaScript Echo Client</title>
</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>
<script>
var echo_websocket;
function init() {
output = document.getElementById("output");
}
function send_echo() {
// 定义websocket的端点地址
var wsUri = "ws://localhost:8080/websocketapp/echo";
writeToScreen("Connecting to " + wsUri);
// 创建websocket对象
echo_websocket = new WebSocket(wsUri);
// 打开websocket
echo_websocket.onopen = function(evt) {
writeToScreen("connected!");
// 发送文本框中的内容到服务端
doSend(textID.value);
}
// 接收到服务端处理的数据
echo_websocket.onmessage = function(evt) {
writeToScreen("Received message: " + evt.data);
// 关闭websocket
echo_websocket.close();
writeToScreen("Closed!");
}
echo_websocket.onerror = function(evt) {
writeToScreen("<span style='color: red'>ERROR:</span>" + evt.data);
echo_websocket.close();
}
}
function doSend(message) {
echo_websocket.send(message);
writeToScreen("Sent 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>
</html>
接下来是客户端是测试代码,点击按钮进行测试。