import java.io.IOException;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
/**
Created by JiaPeng on 2016/2/15.
*/
@ServerEndpoint("/websocket")
public class WebSocketTest {
@OnMessage
public void onMessage(String message, Session session) throws IOException, InterruptedException {
System.out.println("Received: " + message);
session.getBasicRemote().sendText("This is the first server message");
int sendMessages = 0;
while (sendMessages < 10) {
Thread.sleep(5000);
session.getBasicRemote().sendText("This is an intermediate server message. Count: " + sendMessages);
sendMessages++;
}
session.getBasicRemote().sendText("This is the last server message");
}
@OnOpen
public void OnOpen() {
System.out.println("Client connected");
}
@OnClose
public void OnClose() {
System.out.println("Connection closed");
}
}
<!DOCTYPE html>
<html>
<head>
<title>Testing websockets</title>
</head>
<body>
<div>
<input type="submit" value="Start" onclick="start()" />
</div>
<div id="messages"></div>
<script type="text/javascript">
var webSocket =
new WebSocket('ws://127.0.0.1:8080/aaa/websocket');
webSocket.onerror = function(event) {
onError(event)
};
webSocket.onopen = function(event) {
onOpen(event)
};
webSocket.onmessage = function(event) {
onMessage(event)
};
function onMessage(event) {
document.getElementById('messages').innerHTML
+= '<br />' + event.data;
}
function onOpen(event) {
document.getElementById('messages').innerHTML
= 'Connection established';
}
function onError(event) {
alert(event.data);
}
function start() {
webSocket.send('hello');
return false;
}
</script>
</body>
</html>
tomcat:D:\apache-tomcat-7.0.88