1、创建一个spring mvc环境的动态web工程(具体详细步骤不多说)
2、创建一个controller
package com.sunhui.test;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.annotation.Resource;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint(value = "/newwebsocket/{userId}")
public class Webcomment {
@Resource
private Webcomment webcomment;
// 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
// concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
private static CopyOnWriteArraySet<Webcomment> webSocketSet = new CopyOnWriteArraySet<Webcomment>();
// 线程安全的Map
private static ConcurrentHashMap<String, Session> webSocketMap = new ConcurrentHashMap<String, Session>();// 建立连接的方法
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId) {
/*
* 获取从/websocket开始的整条链接,用于获取userId?***=***的参数 String uri =
* session.getRequestURI().toString();
*/
webSocketMap.put(userId, session);
addOnlineCount(); // 在线数加
System.out.println(userId + "进入聊天室");
System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(Session session) {
Map<String, String> map = session.getPathParameters();
webSocketMap.remove(map.get("userId")); // 从set中删除
for (String user : webSocketMap.keySet()) {
System.out.println(user);
}
subOnlineCount(); // 在线数减
System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message
* 客户端发送过来的消息
* @param session
* 可选的参数
*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("来自客户端的消息:" + message);
// 获取用户ID
Map<String, String> map = session.getPathParameters();
String userId = map.get("userId");
for (String user : webSocketMap.keySet()) {
try {
sendMessage(user + "你好,我是" + userId + " " + message,
webSocketMap.get(user));
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 发生错误时调用
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
System.out.println("发生错误");
error.printStackTrace();
}
public void sendMessage(String message, Session session) throws IOException {
if (session.isOpen()) {
session.getAsyncRemote().sendText(message);
}
// this.session.getAsyncRemote().sendText(message);
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
Webcomment.onlineCount++;
}
public static synchronized void subOnlineCount() {
Webcomment.onlineCount--;
}
}
3、创建一个html页面
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>new document</title>
<meta name="generator" content="editplus" />
<meta name="author" content="" />
<meta name="keywords" content="" />
<meta name="description" content="" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="jquery-2.0.3.min.js" type="text/javascript"></script>
</head>
<body>
<center>
Welcome<br />
<input id="text" type="text" />
<button οnclick="send()">发送消息</button>
<hr />
<button οnclick="closeWebSocket()">关闭WebSocket连接</button>
<hr />
<div id="message"></div>
</body>
<script type="text/javascript">
var websocket = null;
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
alert('当前浏览器支持 websocket');
websocket = new WebSocket("ws://127.0.0.1:8080/test/newwebsocket/123");
} else {
alert('当前浏览器 Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function() {
setMessageInnerHTML("WebSocket连接发生错误");
};
//连接成功建立的回调方法
websocket.onopen = function() {
setMessageInnerHTML("WebSocket连接成功");
}
//接收到消息的回调方法
websocket.onmessage = function(event) {
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function() {
setMessageInnerHTML("WebSocket连接关闭");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function() {
closeWebSocket();
}
//将消息显示在网页上
function setMessageInnerHTML(innerHTML) {
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//关闭WebSocket连接
function closeWebSocket() {
websocket.close();
}
//发送消息
function send() {
var message = document.getElementById('text').value;
websocket.send(message);
}
</script>
</html>
4、导入 jquery-xxx.min.js
5、接下来就是测试了。。。。。
效果如下:
到此测试完成。。。