tomcat8 實現websocket demo
阿新 • • 發佈:2018-12-05
程式碼實現:
引用:
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>8.0</version>
<scope>provided</scope>
</dependency>
實現:
package com.xjcy.test.controller; import java.io.IOException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.websocket.MessageHandler; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; @ServerEndpoint("/websocket/{username}") public class SocketTest { private static int onlineCount = 0; private static Map<String, SocketTest> clients = new ConcurrentHashMap<>(); private Session session; private String username; @OnOpen public void onOpen(@PathParam("username") String username, Session session) throws IOException { this.username = username; this.session = session; addOnlineCount(); clients.put(username, this); System.out.println("已連線"); } @OnClose public void onClose() throws IOException { clients.remove(username); subOnlineCount(); } @OnMessage public void onMessage(String message) throws IOException { sendMessageAll(this.username +" say:"+ message); //JSONObject jsonTo = JSONObject.fromObject(message); // if (!jsonTo.get("To").equals("All")){ // sendMessageTo("給一個人", jsonTo.get("To").toString()); // }else{ // sendMessageAll("給所有人"); // } } @OnError public void onError(Session session, Throwable error) { error.printStackTrace(); } public void sendMessageTo(String message, String To) throws IOException { // session.getBasicRemote().sendText(message); //session.getAsyncRemote().sendText(message); for (SocketTest item : clients.values()) { if (item.username.equals(To) ) item.session.getAsyncRemote().sendText(message); } } public void sendMessageAll(String message) throws IOException { for (SocketTest item : clients.values()) { item.session.getAsyncRemote().sendText(message); } } public static synchronized int getOnlineCount() { return onlineCount; } public static synchronized void addOnlineCount() { SocketTest.onlineCount++; } public static synchronized void subOnlineCount() { SocketTest.onlineCount--; } public static synchronized Map<String, SocketTest> getClients() { return clients; } }
頁面實現:
<%@ 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>Insert title here</title> </head> <body> <input type="text" id="msg" style="width: 200px;" /> <input type="button" value="傳送" onclick="send()" /> <input type="button" value="重新連線" onclick="re()" /> <br /> <br /> <textarea cols="80" rows="100" id="content"></textarea> <script type="text/javascript"> var websocket = null; var username = new Date().getTime(); localStorage["user"] = username; openWebSocket(); function openWebSocket() { //判斷當前瀏覽器是否支援WebSocket if ('WebSocket' in window) { websocket = new WebSocket("ws://" + document.location.host + "/test/websocket/" + username); //連線發生錯誤的回撥方法 websocket.onerror = function() { setMessageInnerHTML("WebSocket連線發生錯誤"); }; //連線成功建立的回撥方法 websocket.onopen = function() { setMessageInnerHTML(localStorage["user"] + "連線成功"); } //接收到訊息的回撥方法 websocket.onmessage = function(event) { setMessageInnerHTML(event.data); } //連線關閉的回撥方法 websocket.onclose = function() { setMessageInnerHTML(localStorage["user"] + "連線關閉"); } } else { alert('當前瀏覽器 Not support websocket') } } //監聽視窗關閉事件,當視窗關閉時,主動去關閉websocket連線,防止連線還沒斷開就關閉視窗,server端會拋異常。 window.onbeforeunload = function() { closeWebSocket(); } //關閉WebSocket連線 function closeWebSocket() { websocket.close(); } function re() { closeWebSocket(); websocket = null; openWebSocket(); } var input = document.getElementById('content'); var text = document.getElementById('msg'); function setMessageInnerHTML(msg) { if (input.value != '') input.value = input.value + '\r\n' + msg; else input.value = msg; } function send() { websocket.send(text.value); } </script> </body> </html>