學習WebSocket(一) — HelloWorld

1.引入jar包

    服務器使用的是Tomcat7,它自帶了websocket-api.jar,因此在pom.xml中的javax.websocket-api使用了scope=provided,方便調試。html

<dependencies>
		<!-- servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.0.1</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/javax/javaee-api -->
		<dependency>
			<groupId>javax</groupId>
			<artifactId>javaee-api</artifactId>
			<version>7.0</version>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/javax.websocket/javax.websocket-api -->
		<dependency>
			<groupId>javax.websocket</groupId>
			<artifactId>javax.websocket-api</artifactId>
			<version>1.0</version>
			<scope>provided</scope>
		</dependency>

	</dependencies>

2.編寫服務端代碼

package cn.net.bysoft.websocketapp.lesson1;

import javax.websocket.OnMessage;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/echo")
public class EchoServer {
	
	@OnMessage
	public String echo(String incomingMessage) {
		return "I got this (" + incomingMessage + ") so I am sending it back !";
	}
}

 

    服務端代碼是簡單的POJO,加入了兩個註解,@ServerEndpoint聲明瞭Socket端點,@OnMessage聲明瞭消息處理函數。java

3.編寫客戶端代碼

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Web Socket JavaScript Echo Client</title>
</head>
<body>
	<h1>Echo Server</h1>

	<div style="text-align: left;">
		<form action="">
			<input onclick="send_echo();" value="Press to send" type="button">
			<input id="textID" name="message" value="Hello Web Sockets"
				type="text"> <br>
		</form>
	</div>

	<div id="output"></div>
</body>

<script>
	var echo_websocket;

	function init() {
		output = document.getElementById("output");
	}

	function send_echo() {
		// 定義websocket的端點地址
		var wsUri = "ws://localhost:8080/websocketapp/echo";
		writeToScreen("Connecting to " + wsUri);
		// 建立websocket對象
		echo_websocket = new WebSocket(wsUri);
		
		// 打開websocket
		echo_websocket.onopen = function(evt) {
			writeToScreen("connected!");
			// 發送文本框中的內容到服務端
			doSend(textID.value);
		}
		
		// 接收到服務端處理的數據
		echo_websocket.onmessage = function(evt) {
			writeToScreen("Received message: " + evt.data);
			// 關閉websocket
			echo_websocket.close();
			writeToScreen("Closed!");
		}

		echo_websocket.onerror = function(evt) {
			writeToScreen("<span style='color: red'>ERROR:</span>" + evt.data);
			echo_websocket.close();
		}
	}

	function doSend(message) {
		echo_websocket.send(message);
		writeToScreen("Sent message:" + message);
	}

	function writeToScreen(message) {
		var pre = document.createElement("p");
		pre.style.wordWrap = "break-word";
		pre.innerHTML = message;
		output.appendChild(pre);
	}

	window.addEventListener("load", init, false);
</script>
</html>

    接下來是客戶端是測試代碼,點擊按鈕進行測試。git

源碼地址:https://github.com/XuePeng87/websocketappgithub

相關文章
相關標籤/搜索