Websocket的入门案例
这个例子很简单,首先是模拟用户登入,至于密码什么的就不保存了
<html>
<head>
<title>方允沉</title>
</head>
<body>
<form action="login" method="post">
用户名:<input type="text" name="username"><br>
<input type="submit" value="进入">
</form>
</body>
</html>
然后servlet请求交给了这个servlet类处理,
@webServlet可以取代web.xml的配置信息,这里很显然是取到了jsp传过来的username,然后转发给另一个页面,当然在实际项目中登入后你就会把User对象都存在session域中。
@WebServlet("/login")
public class TestAction extends HttpServlet{
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//取到username
String username=request.getParameter("username");
//存到session
request.getSession().setAttribute("username",username);
request.getRequestDispatcher("/WEB-INF/pages/test2.jsp").forward(request,response);
}
}
然后是test2.jsp页面,浏览器端代码
其中ws://"+document.location.host+"/websocket/"+username,document.location.host可以获取到端口,这里的路径不能加项目名,不然会报404错,websockt对应服务器端的url,username是我想传过去的参数,用于绑定这个握手协议,这样方便一对一发消息时知道发给谁。
<html>
<head>
<title>Title</title>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
<script type="text/javascript">
var websocket = null;
var username='${username}';
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://"+document.location.host+"/websocket/"+username);
} else {
alert('当前浏览器 Not support websocket');
}
//连接发生错误的回调方法
websocket.onerror = function() {
console.log("WebSocket连接发生错误");
};
//连接成功建立的回调方法
websocket.onopen = function() {
console.log("WebSocket连接成功");
}
//接收到消息的回调方法
websocket.onmessage = function(event) {
$("div").append(event.data+"<br>");
}
//连接关闭的回调方法
websocket.onclose = function() {
console.log("WebSocket连接关闭");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function() {
closeWebSocket();
}
//关闭WebSocket连接
function closeWebSocket() {
websocket.close();
}
//发送消息
function send() {
var message = $(".text").val() ;
websocket.send(message);
}
</script>
</head>
<body>
<input type="text" class="text">
<input type="button" value="发送" onclick="send()">
<div id="context">
</div>
</body>
</html>
服务器端代码
这里在servle里不需要多余的配置,但是在struts2框架里请求貌似会被struts拦截,
@ServerEndpoint("/websocket/{username}")就对应客服端的那个url,
@PathParam("username")注解可以得到传过来的username
Map<String, WebSocket>装的是每一个连接。
只要当前页面被加载,就会触发jsp的onOpen()方法和这个类的onOpen()方法,jsp通过send方法发送消息,服务器通过
onMessage()方法处理数据并由接收者的jsp的onmessage()方法处理。
@ServerEndpoint("/websocket/{username}")
public class WebSocket {
private static int onlineCount = 0;
private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>();
private Session session;
private String username;
@OnOpen
public void onOpen(@PathParam("username") String username, Session session) throws IOException {
this.username = username;
this.session = session;
addOnlineCount();
//把该用户放入clients
clients.put(username, this);
sendMessageAll(username+"已经加入");
}
@OnClose
public void onClose() throws IOException {
clients.remove(username);
sendMessageAll(username+"已经退出");
subOnlineCount();
}
@OnMessage
public void onMessage(String message) throws IOException {
//如果想传json,可以在jsp先封装,这里就传字符串了
/*JSONObject jsonTo = JSONObject.fromObject(message);
if (!jsonTo.get("To").equals("All")){
sendMessageTo("给一个人", jsonTo.get("To").toString());
}else{
sendMessageAll("给所有人");
}*/
//这里也只测试群聊,单人对话可以在message中根据传过来的json数据传给相应对象
sendMessageAll(username+":"+message);
}
@OnError
public void onError(Session session, Throwable error) {
error.printStackTrace();
}
public void sendMessageTo(String message, String To) throws IOException {
for (WebSocket item : clients.values()) {
if (item.username.equals(To) )
item.session.getAsyncRemote().sendText(message);
}
}
public void sendMessageAll(String message) throws IOException {
for (WebSocket item : clients.values()) {
item.session.getAsyncRemote().sendText(message);
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocket.onlineCount--;
}
public static synchronized Map<String, WebSocket> getClients() {
return clients;
}
}
效果图: