什么是webSocket?
webSocket 是解决服务器端和客户端通信实时的技术。ajax也可以通信,但是他做不到实时。在webSocket之前我们想要实时效果,都是要通过轮询的方式,显然这样很浪费资源。
webSocket 的强大在于,比起ajax 需要从客户端发起请求,webSocket的 服务端与客户端可以相互实时推送消息。
如何使用webSocket?
首先你得有一个支持它的浏览器。(IE 是不支持的)
创建socket后 ,客户端可以通过 onopen,onmessage,onclose,onerror 这四个时间对socket进行响应。
举个栗子:
环境:tomcat7或以上。jdk7 或以上
1.webSocketTest.java
package instance;
import java.io.IOException;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
<span style="color:#ff6666;">@ServerEndpoint("/websocket")</span>
public class WebSocketTest {
@OnMessage
public void onMessage(String message, Session session)
throws IOException, InterruptedException {
// Print the client message for testing purposes
System.out.println("Received: " + message);
// Send the first message to the client
session.getBasicRemote().sendText("This is the first server message");
// Send 3 messages to the client every 5 seconds
int sentMessages = 0;
while(sentMessages < 3){
Thread.sleep(5000);
session.getBasicRemote().
sendText("This is an intermediate server message. Count: "
+ sentMessages);
sentMessages++;
}
// Send a final message to the client
session.getBasicRemote().sendText("This is the last server message");
}
@OnOpen
public void onOpen() {
System.out.println("Client connected");
}
@OnClose
public void onClose() {
System.out.println("Connection closed");
}
}
2.page.html
<!DOCTYPE html>
<html>
<head>
<title>Testing websockets</title>
</head>
<body>
<div>
<input type="submit" value="Start" οnclick="start()" />
</div>
<div id="messages"></div>
<script type="text/javascript">
var webSocket =
new WebSocket('ws://localhost:8080/webScoket/<span style="color:#ff6666;">websocket</span>');
webSocket.onerror = function(event) {
onError(event)
};
webSocket.onopen = function(event) {
onOpen(event)
};
webSocket.onmessage = function(event) {
onMessage(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.data);
}
function start() {
webSocket.send('hello');
return false;
}
</script>
</body>
</html>
这里要注意:
var webSocket =
new WebSocket('ws://localhost:8080/webScoket/websocket');
其中:一个是项目名称,一个是注解的服务器名称
到此你启动服务器,运行page.html
出现如图,就说明成功了