首發:我的博客javascript
在tomcat7以後的版本,寫個websocket服務程序很是容易——
如如下代碼所示,當客戶端創建了一個鏈接併發送了一些什麼內容到服務器,服務器將每隔兩秒返回一個字符串「world」。
之因此演示每兩秒返回一次是爲了說明這是長鏈接而不是短鏈接。html
import java.io.IOException;java
import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;web@ServerEndpoint("/test")
public class MyTest {spring@OnMessage
public void onMessage(String message, Session session)
throws IOException, InterruptedException {
System.out.println("客戶端說:" + message);
while(true){
session.getBasicRemote().sendText("world");
Thread.sleep(2000);
}
}
}tomcat
網頁只須要這樣寫:服務器
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello WebSocket</title>
</head>
<body>
<div id="content"></div>
<button onclick="sayHello()">打招呼</button>websocket<script type="text/javascript">
var webSocket =
new WebSocket('ws://localhost:8080/dyna/test');sessionwebSocket.onerror = function(event) {
onError(event)
};併發webSocket.onopen = function(event) {
onOpen(event)
};webSocket.onmessage = function(event) {
onMessage(event)
};function onMessage(event) {
document.getElementById('content').innerHTML += '<br />服務器說:' + event.data;
}function onOpen(event) {
document.getElementById('content').innerHTML = '鏈接成功';
}function onError(event) {
document.getElementById('content').innerHTML = '出現錯誤';
}function sayHello() {
webSocket.send('hello');
return false;
}
</script>
</body>
</html>
調試的時候發現tomcat7的支持不是特別好,
在eclipse裏添加server而後在上面跑項目,不支持websocket;
用在server.xml裏添項目的方式,也不支持websocket。
因此換成tomcat8,在eclipse裏添加server而後跑項目,websocket也好使。
這樣調試就很方便了。
TODO:
1.maven的tomcat7:run個別項目出現奇怪的問題;maven集成tomcat8的實驗有時間作作
2.spring4對websocket的支持怎麼試都不成功,有時間攻克它。
3.把今天學的即便通信技術與websocket結合,作網頁版qq之類的demo。
長期歡迎項目合做機會介紹,項目收入10%用於酬謝介紹人。新浪微博:@冷鏡,QQ:908789432。