java:
package webSocket;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/websocket/{user}")
public class WebSocketTest {
@OnMessage
public void onMessage(String message, Session session,@PathParam(value = "user")String user){
try {
System.err.println("session.getRequestParameterMap()>>"+session.getRequestParameterMap());
System.err.println("user>>>>>>>>>>>>>>>>"+user);
// 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 < 30) {
Thread.sleep(5000);
session.getBasicRemote().sendText("This is an intermediate server message. Count: " + sentMessages++);
}
// Send a final message to the client
session.getBasicRemote().sendText("This is the last server message");
} catch (Exception e) {
e.printStackTrace();
}
}
@OnOpen
public void onOpen() {
System.out.println("Client connected");
}
@OnClose
public void onClose() {
System.out.println("Connection closed");
}
}
备注:
1、上面这种方式类似于servlet,不需要main方法, 只需要url中写明就可以访问到
2、上面中的引入类我这里是tomcat7提供的,而不是java7 引入的
新建一个html页面,从前端发送请求
<!DOCTYPE html>
<html>
<head>
<title>Testing websockets</title>
</head>
<body>
<div>
<input type="submit" value="Start" onclick="start()" />
</div>
<div id="messages"></div>
<script type="text/javascript">
var webSocket = new WebSocket('ws://localhost:8080/a/websocket');
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);
alert("error");
}
function start() {
webSocket.send('hello');
return false;
}
</script>
</body>
</html>
IE是要在IE10才支持,websocket是 HTML5的一个新特性。