小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

花了20分鐘,給女朋友們寫了一個web版群聊程序

 路人甲Java 2020-01-15

WebSocket詳解

WebSocket 是 HTML5 開始提供的一種在單個 TCP 連接上進行全雙工通訊的協(xié)議。

WebSocket 使得客戶端和服務(wù)器之間的數(shù)據(jù)交換變得更加簡單,允許服務(wù)端主動向客戶端推送數(shù)據(jù)。在 WebSocket API 中,瀏覽器和服務(wù)器只需要完成一次握手,兩者之間就直接可以創(chuàng)建持久性的連接,并進行雙向數(shù)據(jù)傳輸??梢哉fWebSocket的出現(xiàn),使得瀏覽器具備了實時雙向通信的能力

在 WebSocket API 中,瀏覽器和服務(wù)器只需要做一個握手的動作,然后,瀏覽器和服務(wù)器之間就形成了一條快速通道。兩者之間就直接可以數(shù)據(jù)互相傳送。

原來為了實現(xiàn)推送,很多公司用的是Ajax 輪詢,即按照特定的時間間隔,由瀏覽器對服務(wù)器發(fā)出HTTP請求,然后由服務(wù)器返回最新的數(shù)據(jù)給客戶端的瀏覽器。這種傳統(tǒng)的模式帶來很明顯的缺點,即瀏覽器需要不斷的向服務(wù)器發(fā)出請求,然而HTTP請求可能包含較長的頭部,其中真正有效的數(shù)據(jù)可能只是很小的一部分,顯然這樣會浪費很多的帶寬等資源。而websocket就可以解決這些問題。

在Spring Boot中使用WebSocket

1.pom文件增加依賴

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency>

2.增加配置

@Configurationpublic class WebSocketConfig {@Beanpublic ServerEndpointExporter serverEndpointExporter() {return new ServerEndpointExporter();}}

3.Java代碼

@Component@ServerEndpoint("/websocket")public class WebSocketServerController {// 收到消息調(diào)用的方法@OnMessagepublic void onMessage(String message) {System.out.println("收到的消息為 " + message);}// 建立連接調(diào)用的方法@OnOpenpublic void onOpen() {System.out.println("Client connected");}// 關(guān)閉連接調(diào)用的方法@OnClosepublic void onClose() {System.out.println("Connection closed");}// 傳輸消息錯誤調(diào)用的方法@OnErrorpublic void OnError(Throwable error) {System.out.println("Connection error");}}

4.前端代碼

<!DOCTYPE html><html><head><title>Testing websockets</title></head><body>
  <div><textarea rows="3" cols="20" id="content"></textarea><br><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)};
	
	webSocket.onclose = function(event) {  onClose(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);}function onClose(event) {  alert(event);}function start() {
	  var text = document.getElementById('content').value;  webSocket.send(text);}
  </script></body></html>

所以你看websocket其實很簡單,前后端各寫4個事件方法就行了(當(dāng)然你也可以省略一些方法)

1.建立連接
2.收到消息
3.傳輸消息失敗
4.關(guān)閉連接

事件和具體會話關(guān)聯(lián)

如果事件想和具體會話關(guān)聯(lián),方法上只要加Session參數(shù)就行(4種事件類型的方法上都可加)

舉個例子,直接將用戶發(fā)送給服務(wù)端的話再返回給客戶端

// 收到消息調(diào)用的方法@OnMessagepublic void onMessage(Session session, String message) {try {
		session.getBasicRemote().sendText(message);} catch (IOException e) {
		e.printStackTrace();}}

在這里插入圖片描述
傳遞參數(shù)

方法上加@PathParam參數(shù)即可

@Component@ServerEndpoint("/websocket/{sid}")public class WebSocketServerController
@OnOpenpublic void onOpen(@PathParam("sid") String sid) {
	System.out.println("Client connected");}

實現(xiàn)一個在線群聊

后端接口

@Slf4j@Component@ServerEndpoint("/groupChat/{sid}/{username}")public class GroupChatController {// 保存 組id->組成員 的映射關(guān)系private static ConcurrentHashMap<String, List<Session>> groupMemberInfoMap = new ConcurrentHashMap<>();// 收到消息調(diào)用的方法,群成員發(fā)送消息@OnMessagepublic void onMessage(@PathParam("sid") String sid,  @PathParam("username") String username, String message) {List<Session> sessionList = groupMemberInfoMap.get(sid);// 先一個群組內(nèi)的成員發(fā)送消息sessionList.forEach(item -> {try {String text = username + ": " + message;item.getBasicRemote().sendText(text);} catch (IOException e) {e.printStackTrace();}});}// 建立連接調(diào)用的方法,群成員加入@OnOpenpublic void onOpen(Session session, @PathParam("sid") String sid) {List<Session> sessionList = groupMemberInfoMap.get(sid);if (sessionList == null) {sessionList = new ArrayList<>();groupMemberInfoMap.put(sid,sessionList);}sessionList.add(session);log.info("Connection connected");log.info("sid: {}, sessionList size: {}", sid, sessionList.size());}// 關(guān)閉連接調(diào)用的方法,群成員退出@OnClosepublic void onClose(Session session, @PathParam("sid") String sid) {List<Session> sessionList = groupMemberInfoMap.get(sid);sessionList.remove(session);log.info("Connection closed");log.info("sid: {}, sessionList size: {}", sid, sessionList.size());}// 傳輸消息錯誤調(diào)用的方法@OnErrorpublic void OnError(Throwable error) {log.info("Connection error");}}

前端代碼很簡單,放github了
地址為:https://github.com/erlieStar/spring-boot-websocket

下面來看效果
在這里插入圖片描述
注意先連接,后發(fā)送
在這里插入圖片描述
在線開房地址:
http://www.:8090/

參考博客

好文
[1]https://blog.csdn.net/moshowgame/article/details/80275084
[2]https://www.jianshu.com/p/d79bf8174196
[3]https://www./tutorials/java-ee-html5-websocket-example
一個群聊程序
[4]https://blog.csdn.net/moshowgame/article/details/80275084

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多