1 开发环境 : myeclipse10 + tomcat7 + jdk1.7
2 需要导入jar包(tomcat7自己含有这2个jar包)
2.1 tomcat7-websocket.jar
2.2 websocket-api.jar
3 项目截图
4 ChartServlet.java 处理用户登录
package com.lanqiao.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/chart") public class ChartServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String name = req.getParameter("username"); req.getSession().setAttribute("name", name); resp.sendRedirect("chart.jsp"); } }5.login.jsp 用户登录 jsp
<body> <form action="chart"> 用户名:<input type="text" name="username"/> <input type="submit" value="登录"/> </form> </body>
6. server.java 消息广播
package com.lanqiao.servlet; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashSet; import java.util.Set; import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; //声明当前是一个websocket类 @ServerEndpoint("/socket") public class Server { private Session session; private String username; //存储用户名和server的对应关系 private static Set<Server> users = new HashSet<Server>(); //监听建立连接 @OnOpen public void open(Session session){ this.session=session; //获取登录用户名 username = session.getQueryString().split("=")[1]; users.add(this); String message="欢迎" + this.username + "加入聊天室"; broadcast(message); } //监听连接关闭 @OnClose public void close(Session session){ //关闭websocket users.remove(this); broadcast(this.username + "退出聊天室"); } //监听用户发送的消息并向每个客户端推送消息 @OnMessage public void sendMessage(String message){ broadcast("【" + this.username + "】" + getDatetime(new Date()) + " : " + message); } public void broadcast(String message){ for(Server client : users){ try { synchronized (client) { client.session.getBasicRemote().sendText(message); } } catch (IOException e) { users.remove(client); try { client.session.close(); } catch (IOException e1) { e.printStackTrace(); } } } } private static String getDatetime(Date date) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return format.format(date); } }7.chart.jsp 聊天窗口