webSocket
1.WebSocket简单介绍
随着互联网的发展,传统的HTTP协议已经很难满足Web应用日益复杂的需求了。近年来,随着HTML5的诞生,WebSocket协议被提出,它实现了浏览器与服务器的全双工通信,扩展了浏览器与服务端的通信功能,使服务端也能主动向客户端发送数据,Socket可以使用TCP/IP协议或UDP协议,
下面使用一个示例来如何使用webSocket:
1.1.需要添加的maven依赖
<!-- https://mvnrepository.com/artifact/javax.websocket/javax.websocket-api --> <!-- 核心依赖--> <dependency> <groupId>javax.websocket</groupId> <artifactId>javax.websocket-api</artifactId> <version>1.1</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.5</version> </dependency>
1.2.WebSocket服务器端
@ServerEndpoint("/chat/server/{userName}") public class ChatServer { /** * 当客户端有连接时调用此方法 */ @OnOpen public void onOpen(Session session,@PathParam("userName") String userName){ System.out.println("连接人"+userName); session.getUserProperties().put("user",userName); } @OnMessage public void onMessage(String message, Session session) throws Exception{ System.out.println("接收消息..." + message); //将消息发送给所有人 sendAllUser(message, session); } /** * 当客户端关闭或者断开连接时,服务端会调用此方法 * @param session */ @OnClose public void opnClose(Session session) throws IOException{ System.out.println("客户端失去连接..."); //关闭会话 session.close(); } public void sendAllUser(String message,Session session) throws Exception { //获取所有人的会话对象 Set<Session> users = session.getOpenSessions(); //获取发送人发给所有人 String sendUser = session.getUserProperties().get("user").toString(); //将所有数据封装成一个对象,以json 的数据格式发送给前端 ResponseVo vo = new ResponseVo(); vo.setMessage(message); vo.setUserName(sendUser); Date date = new Date(); String dateStr = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(date); vo.setDate(dateStr); Gson gson = new Gson(); String json = gson.toJson(vo); for (Session user : users) { user.getBasicRemote().sendText(json); } } /** * 连接错误时执行 */ @OnError public void onError(Throwable t) { t.printStackTrace(); }
1.3.前端代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="loginDiv"> 用户名:<input type="text" id="userName" name="userName"/> <input type="button" id="login" value="login"/> </div> <div id="container" style="display: none"> <div id="content"></div> <input type="text" name="msg" id="msg"/> <input type="button" id="send" value="send"/> </div> <script src="js/jquery-3.3.1.min.js"></script> <script> $(function(){ var ws; //登陆 $('#login').on('click',function(){ var userName = $('#userName').val(); //创建websocket对象并连接服务端 ws = new WebSocket('ws://localhost:8080/chat/server/' + userName); //客户端打开连接时会回调此方法 /*ws.onopen = function(){ //... }*/ //客户端关闭或断开连接时执行此方法 /*ws.onclose = function(){ //... }*/ //接收服务端发送的消息 ws.onmessage = function(message){ var data = JSON.parse(message.data); $('#content').append(data.date+","+data.userName+":"+data.message+ "<br>"); } $('#loginDiv').css('display','none'); $('#container').css('display','block'); }); //发送消息 $('#send').on('click',function(){ var msg = $('#msg').val(); //发送消息 ws.send(msg); }); }); </script> </body> </html>
1.4:运行效果