創建一個web項目 導入依賴: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema- ...
創建一個web項目
導入依賴:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.chu</groupId> <artifactId>webSocket</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <!-- servlet-api--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <!-- websocket-api--> <dependency> <groupId>javax.websocket</groupId> <artifactId>javax.websocket-api</artifactId> <version>1.1</version> <!-- 設置作用域 預設compile 編譯 測試 運行 provided 編譯 測試 runtime 測試 運行 test 測試--> <scope>provided</scope> </dependency> <!-- JSON轉換--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.7.4</version> </dependency> </dependencies> <!-- <build>--> <!-- <plugins>--> <!-- maven自帶的tomcat插件 需要配置對應的命令 tomcat7:run--> <!-- <plugin>--> <!-- <groupId>org.apache.tomcat.maven</groupId>--> <!-- <artifactId>tomcat7-maven-plugin</artifactId>--> <!-- <version>2.2</version>--> <!-- <configuration>--> <!-- <port>80</port>--> <!-- <path>/</path>--> <!-- <uriEncoding>UTF-8</uriEncoding>--> <!-- </configuration>--> <!-- </plugin>--> <!-- </plugins>--> <!-- </build>--> </project>
controller層代碼:
package com.chu.controller; import com.fasterxml.jackson.databind.ObjectMapper; import javax.websocket.*; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.util.HashMap; import java.util.Map; /* 小楚想要發送信息給小趙 這個信息會先存儲在伺服器 再由伺服器發送給小趙 */ @ServerEndpoint("/chat/{name}") public class ChatSocket { //定義一個Map集合,用來存放登陸到伺服器的客戶名稱和Session private static Map<String,Session> mapMessage = new HashMap<>(); //首先,方法名稱可以自定義 // *形參---name---Session @OnOpen//會話開始 public void onOpen(@PathParam("name")String name, Session session){ System.out.println("onOpen....."+name); //key-----name value-----session mapMessage.put(name,session); } //客戶機信息處理 * 形參---Session session ---String message @OnMessage public void onMessage(Session session,String message){ System.out.println("onMessage....."+message); //服務端給客戶端發消息,走的不是HTTP 而是直接推送過去了 //獲取JSON對象 ObjectMapper mapper = new ObjectMapper(); try { //獲取JSON格式的信息 Map<String,String> map = mapper.readValue(message, Map.class); //獲取需要發送的信息:content String content = map.get("content"); //獲取接收信息者:小趙 String receive = map.get("receive"); //從事先定義好的Map中獲取小趙的Session Session receiveSession = mapMessage.get(receive); //如果小趙的Session為null if(receiveSession==null){ //響應:對方不線上 session.getAsyncRemote().sendText("對方不線上"); }else{ //否則將接收到的信息發送給小趙 receiveSession.getAsyncRemote().sendText(content); } } catch (IOException e) { e.printStackTrace(); } } //會話結束 @OnClose public void onClose(Session session){ System.out.println("onClose....."+session); } //會話出現異常 @OnError public void onError(Session session,Throwable e){ try { e.printStackTrace(); session.close(); } catch (IOException ex) { ex.printStackTrace(); } } }
jsp代碼:
1 <body> 2 <div align="center" style="padding-top: 50px"> 3 4 發送者<input id="sendOut"><br> 5 6 接收者<input id="receive"><br> 7 8 信息<input id="content"><br> 9 10 <input type="button" value="註冊" onclick="reg()"> 11 12 <input type="button" value="提交" onclick="sendmsg()"><br> 13 14 <span id="list"></span> 15 16 <script type="text/javascript"> 17 var ws; 18 // 註冊按鈕 19 function reg() { 20 // 註冊路徑 加上自己的用戶名 21 ws = new WebSocket("ws://localhost:8080/chat/"+document.getElementById("sendOut").value) 22 //接收伺服器信息並顯示 23 ws.onmessage = function (msg) { 24 //接收伺服器信息 25 var message = msg.data 26 //獲取展示信息的位置 27 var former = document.getElementById("list") 28 former.innerHTML=former.innerHTML+"...他說"+message 29 } 30 } 31 function sendmsg() { 32 // 獲取接收者 33 var receive = document.getElementById("receive").value 34 //獲取發送的內容 35 var content = document.getElementById("content").value 36 //以JSON的方式發送到伺服器 37 ws.send('{"receive":"'+receive+'","content":"'+content+'"}') 38 //獲取展示信息的位置 39 var former = document.getElementById("list") 40 former.innerHTML=former.innerHTML+"...你說"+content 41 } 42 </script> 43 </div> 44 </body>