基于tomcat7和jdk1.7的websocket 群聊

时间:2021-10-11 19:07:13

1 开发环境 : myeclipse10 + tomcat7 + jdk1.7

2 需要导入jar包(tomcat7自己含有这2个jar包)

 2.1 tomcat7-websocket.jar

 2.2 websocket-api.jar

3 项目截图

基于tomcat7和jdk1.7的websocket 群聊

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 聊天窗口
<body>
    <input type="text" id="text" name="message"/>
    <input type="button" value="发送" onclick="sendMessage()"/>
    <div id="msg">
    </div>
    <script type="text/javascript">
    	//创建socket
    	var socket = new WebSocket("ws://127.0.0.1:8080/WebSocket/socket?name=${name}");
    	//连接服务器
    	socket.onopen=function(){
    		console.log("连接服务器");
    	}
    	//发送失败
    	socket.onerror=function(event){
    		console.log(event.data);
    	}
    	//接收服务器推送的消息
    	socket.onmessage=function(event){
    		var msg = document.getElementById("msg");
    		var div = document.createElement("div");
    		div.innerHTML=event.data;
    		msg.appendChild(div);
    	}
    	//将接收到的信息渲染到浏览器页面
    	function sendMessage(event){
    		var text = document.getElementById("text").value;
    		socket.send(text);
    	}
    </script>
  </body>

7 操作方法login.jsp随便输入用户名登录,会自动跳转到chart.jsp,在该页面进行聊天

基于tomcat7和jdk1.7的websocket 群聊