java SpringBoot+webSocket聊天小程式 (複製程式碼即可用)
1。後端程式碼
package test.conntroller.socket;
import java.util.HashMap; import java.util.HashSet; import java.util.Random; import java.util.Set; import java.util.UUID; import java.util.concurrent.CopyOnWriteArraySet;
import javax.annotation.PostConstruct; 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;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component;
@ServerEndpoint(value="/webSocket/{nickname}") //webSocket連線點對映 @Component public class MyWebSocket { @Autowired private JdbcTemplate jdbc; private static JdbcTemplate jdbcs; //儲存每個客戶端對應的MyWebSocket物件 private static CopyOnWriteArraySet<MyWebSocket>webSocketSets = new CopyOnWriteArraySet<MyWebSocket>(); private Session session; //當前會話的session private static String nickname; //解決spring注入不上問題 @PostConstruct public void init(){ jdbcs=jdbc; } /** * 成功建立連線的方法 * */ @OnOpen public void onOpen(Session session,@PathParam("nickname")String nickname){ createUser(nickname); this.nickname=nickname; this.session=session; webSocketSet.add(this); System.err.println(this); System.out.println(session); //this.session.getAsyncRemote().sendText(nickname+"上線了"+"當前線上人數為"+webSocketSet.size()+"人"); for (MyWebSocket myWebSocket : webSocketSet) { if(myWebSocket==this){ session.getAsyncRemote().sendText(nickname+"連線成功"+"當前線上人數為"+webSocketSet.size()+"人"); }else session.getAsyncRemote().sendText(nickname+"上線了"+"當前線上人數為"+webSocketSet.size()+"人"); } } private void createUser(String nickname2) { // TODO Auto-generated method stub String uuid = UUID.randomUUID().toString(); this.jdbcs.update("insert into demo(id,name)values(?,?)",new Object[]{uuid,nickname2}); } /** * 連線關閉的方法 * * */ @OnClose public void onClose(Session session){ webSocketSet.remove(this); } /** * 接收客戶端訊息後呼叫的方法 * * */ @OnMessage public void onMessage(String message,Session session,@PathParam("nickname")String nickname){ broadcast(message,nickname); } private void broadcast(String message,String nickname) { // TODO Auto-generated method stub for (MyWebSocket myWebSocket : webSocketSet) { if(myWebSocket==this){ session.getAsyncRemote().sendText("<span style=\"color:red;float:right\">"+message+":"+nickname+"</span>"); }else{ session.getAsyncRemote().sendText(nickname+":"+message); } } } /** *發生錯誤的方法 * * */ @OnError public void onError(Session session,Throwable error){ System.out.println("發生錯誤"); error.printStackTrace(); } }
2.前端程式碼
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Insert title here</title> <style> #message{ margin-top:20px; border:1px solid gray; padding:20px; } input{ text-align:center; } </style> </head> <body>
<button onclick="conectWebSocket()">連線WebSocket</button> <button onclick="closeWebSocket()">斷開連線</button> <br></br> 訊息:<input type="text" id="text" /> <button onclick="send()">傳送訊息</button> <div id="message" style="width: 500px;height: 500px;overflow-y:scroll"> </div> <script type="text/javascript"> //連線物件 var websocket = null; var nickname = null; function conectWebSocket(){ nickname = document.getElementById("nickname").value; if(nickname == ''){ alert("請輸入暱稱"); return; } //判斷當前的瀏覽器是否支援websocket. if("WebSocket" in window){ websocket = new WebSocket("ws://127.0.0.1:8081/webSocket/"+nickname); }else{ alert("不支援"); return false; } //連線成功的方法. websocket.onopen = function(event){ setMessgeHtml("連線成功"); } //連線關閉. websocket.onclose = function(event){ setMessgeHtml("連線關閉"); } //連線異常. websocket.onerror = function(event){ setMessgeHtml("連線異常"); } websocket.onmessage = function(event){ setMessgeHtml(event.data); } } function setMessgeHtml(msg){ var message = document.getElementById("message"); message.innerHTML += msg+"<br/>"; } /** 傳送訊息. */ function send(){ var message = document.getElementById("text").value; document.getElementById("text").value=''; websocket.send(message);//將json物件轉換為json字串. } </script> </body> </html>