一、IDEA建立Module,結構如圖(Tomcat8.0)javascript
二、引入jar包:javax.websocket-api.jarhtml
三、新建WebSocketTest類java
import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; import java.io.IOException; /** * 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"); } }
四、index.jsp頁面代碼web
<!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://localhost:8080/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>