Eclipse創建WebSocket

要求:Tomcat必須7.0以上,創建Dynamic web project

1.前臺代碼
index.html
注意:把js文件引一下,或者用百度的

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<script type="text/javascript" src="js/jquery.min.js"></script>
		<title>webSocket頁面</title>

		<style type="text/css">
			body {
				background: url("https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2629712266,1629089266&fm=26&gp=0.jpg");
			}//背景圖爲百度圖片
			/*右下角提示框樣式start*/
			
			.pop {
				position: fixed;
				right: 10px;
				bottom: 10px;
				box-shadow: 0px 5px 15px rgba(0, 0, 0, 0.5);
				display: block;
				opacity: 0.9;
			}
			
			.popHead {
				background: #fff;
				width: 250px;
				height: 10px;
				line-height: 10px;
				padding: 10px;
				border: 1px solid #aaa;
				font-size: 16px;
			}
			
			.popHead a {
				float: right;
				color: #f23456;
				cursor: pointer;
				display: block;
				text-decoration: none;
			}
			
			.popHead span {
				font-size: 15px;
			}
			
			.popContext {
				height: 80px;
				padding: 15px;
				background: #f1f1f1;
			}
		</style>
		<script type="text/javascript">
			//提示內容,封裝方法
			function pop(title, text, time) {
				if(title == undefined) {
					title = "消息提示";
				}
				if(text == undefined) {
					text = "收到新的消息";
				}
				if(time == undefined) {
					time = 2000;
				}
				//將消息標題,內容放到一個地方
				$("#popHead span").html(title);
				$("#popTxt").html(text);
				 //框框顯示出來,每隔三秒自動消失
				$("#pop").show(100, "linear", function() {
					setTimeout("closePop()", time);
				}); 
			}
			//關閉消息彈出框
			function closePop() {
				$("#pop").hide();
			}
		</script>
	</head>
	<script type="text/javascript">
		var websocket = null;
		if('websocket' in window) {
			console.log(window); 
			websocket = new WebSocket("ws://localhost:8080/testWeb/MsgWebSocket");
		} else {
			alert("警告!您的瀏覽器不支持webSocket!!")
		}
		/*瀏覽器關閉前,回調函數,防止服務端拋異常 */
		window.onbeforeunload = function() {
				websocket.close();
			}
			/*當瀏覽器接收到websocket消息*/
		websocket.onmessage = function(event) {
				//console.log(event); //調試數據
				popMsg(event.data);
			};
			/*消息來臨時,彈出框顯示消息,並播放語音,將消息追加到當前頁面div中 */
		function popMsg(msg) {
			$("#allMsg").append(msg + "<br/>");
			//封裝一個消息彈出的方法(消息標題,消息內容,消息顯示時長)
			pop("消息提示", msg, 3000);
			//語音播放,自己搜索百度語音api平臺
			var obj = $('<audio src="http://fanyi.baidu.com/gettts?lan=zh&amp;text=' + msg + '&amp;spd=5&amp;sorce=web"  autoplay> </audio>');
			$("#pop").append(obj);
		}

		/* [發送信息]案例*/
		function sendMsg() {
			var message = $("#txtMsgSend").val();
			$("allMsg").append(message + "<br/>");
			websocket.send(message);
		}
		/*[關閉]*/
		function closeMsg() {
			websocket.send("有用戶掉線了!!");
			websocket.close();
		}
	</script>

	<body>
		<input type="text" name="txtMsgSend" id="txtMsgSend" />
		<button onclick="sendMsg()">發送信息</button>
		<button onclick="closeMsg()">關閉</button>
		<div id="allMsg">
		</div>
		<!--
    	作者:[email protected]
    	時間:2018-10-23
    	描述:右下角消息提示框
    -->
		<div id="pop" class="pop">
			<div id="popHead" class="popHead">
				<a title="關閉" onclick="closePop()">關閉</a><span></span>
				<div id="popTxt" class="popContext">

				</div>
			</div>
		</div>
	</body>

</html>

2.後臺代碼
在src創建class
我的是 com.fcy.service
MsgWebSocket.java

package com.fcy.service;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
/**
 * webSocket的服務端:負責接收所有瀏覽器的消息,並負責轉發
 * @author fansds
 *
 */
@ServerEndpoint(value="/MsgWebSocket")
public class MsgWebSocket {
		//當每一個連接來的時候都會實例化一個MsgWebSocket
		private static CopyOnWriteArraySet<MsgWebSocket> webSockets =new CopyOnWriteArraySet<>();
		//與任何一個客戶端的連接都有會話
		private Session session;
		@OnOpen
		public void onOpen(Session session) {
			this.session=session;
			webSockets.add(this);
			sendMsgToOthers("有新用戶上線");
		}
		@OnClose
		public void onClose(Session session) {
			this.session=session;
			webSockets.remove(this);
		}
		//給其他所有用戶發送消息,不給自己發
		private void sendMsgToOthers(String message) {
			for(MsgWebSocket item:webSockets) {
				System.out.println(this.session);
				//不給自己發送(誰發的消息,就不給誰轉發)
				if (this.session.getBasicRemote().equals(item.session.getBasicRemote())) {
					continue;
				}
				//封裝一個給每個session發送消息的方法
				item.sendMessage(message);
			}
		}
		private void sendMessage(String message) {
			
			try {
				this.session.getBasicRemote().sendText(message);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		/*
		 * 當服務器接收到消息的時候,做消息轉發
		 */
		@OnMessage
		public void onMessage(String message,Session session) {
				System.out.println("來自客戶端的消息:"+message);
				//當有消息來臨時,給除去自己外的所有人發送消息
				sendMsgToOthers(message);
		}
}

3.啓動Tomcat測試效果圖
打開兩個頁面進行交互,互發信息
效果圖
總結:WebSocket 是一種網絡通信協議。WebSocket 是 HTML5 開始提供的一種在單個 TCP 連接上進行全雙工通訊的協議。
websocket的屬性及方法:
在這裏插入圖片描述
在這裏插入圖片描述

在這裏插入圖片描述

寫的不好,僅供參考。歡迎大神指點

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章