First of all, I would like to declare to you: jdk 7 is required, tomcat needs to support the websocket version
1.InitServlet
This class is mainly used to initialize the map repository that constructs the future storage of user identity information, use its initialization method Init to initialize the repository, and use its static method GetSocketList to obtain the corresponding user identity information.
webSocket, I think MessageInbound is used to identify the login's information, use it to find the corresponding person and push messages. Each login will generate a MessageInbound.
Here HashMap<String,MessageInbound>: string stores the login id of the user session, and MessageInbound stores the identity information required for pushing. The above is personal oral understanding.
package socket; import java.nio.CharBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import org.apache.catalina.websocket.MessageInbound; public class InitServlet extends HttpServlet { private static final long serialVersionUID = -L; //private static List<MessageInbound> socketList; private static HashMap<String,MessageInbound> socketList; public void init(ServletConfig config) throws ServletException { // InitServlet.socketList = new ArrayList<MessageInbound>(); InitServlet.socketList = new HashMap<String,MessageInbound>(); super.init(config); System.out.println("Server start============"); } public static HashMap<String,MessageInbound> getSocketList() { return InitServlet.socketList; } /* public static List<MessageInbound> getSocketList() { return InitServlet.socketList; } */} 2.MyWebSocketServlet
The websocket is used to establish a connection servlet. When establishing a connection, first get the userId of the login in session, and pass the userId when calling the MyMessageInbound constructor.
package socket; import java.io.IOException; import java.io.PrintWriter; import java.nio.CharBuffer; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.catalina.websocket.StreamInbound; import org.apache.catalina.websocket.WebSocketServlet; /** * * @ClassName: MyWebSocketServlet * @Description: Created when establishing a connection* @author mangues * @date -- */ public class MyWebSocketServlet extends WebSocketServlet { public String getUser(HttpServletRequest request){ String userName = (String) request.getSession().getAttribute("user"); if(userName==null){ return null; } return userName; // return (String) request.getAttribute("user"); } @Override protected StreamInbound createWebSocketInbound(String arg, HttpServletRequest request) { System.out.println("#############"); return new MyMessageInbound(this.getUser(request)); } } 3. The onOpen method calls the map identity repository of the InitServlet.
Put the user userId and the websocket identity information corresponding to the logged-in user MessageInbound (userId can be used to find the identity required for pushing MessageInbound)
onTextMessage: used to get messages and send messages
package socket; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.util.HashMap; import org.apache.catalina.websocket.MessageInbound; import org.apache.catalina.websocket.WsOutbound; import util.MessageUtil; public class MyMessageInbound extends MessageInbound { private String name; public MyMessageInbound() { super(); } public MyMessageInbound(String name) { super(); this.name = name; } @Override protected void onBinaryMessage(ByteBuffer arg) throws IOException { // TODO Auto-generated method stub } @Override protected void onTextMessage(CharBuffer msg) throws IOException { // map after the message sent by the user HashMap<String,String> messageMap = MessageUtil.getMessage(msg); // Processing message class//Upline user collection class map HashMap<String, MessageInbound> userMsgMap = InitServlet.getSocketList(); String fromName = messageMap.get("fromName"); //The message comes from the userId String toName = messageMap.get("toName"); //The message is sent to the user's userId //Get the userMessageInbound messageInbound = userMsgMap.get(toName); //The MessageInbound sent to the user in the warehouse if(messageInbound!=null){ //If the message exists to the user, perform operation WsOutbound outbound = messageInbound.getWsOutbound(); String content = messageMap.get("content"); //Get message content String msgContentString = fromName + " " + content; //Construct the sent message//Send out the content CharBuffer toMsg = CharBuffer.wrap(msgContentString.toCharArray()); outbound.writeTextMessage(toMsg); // outbound.flush(); } /* for (MessageInbound messageInbound : InitServlet.getSocketList()) { CharBuffer buffer = CharBuffer.wrap(msg); WsOutbound outbound = messageInbound.getWsOutbound(); outbound.writeTextMessage(buffer); outbound.flush(); } */ } @Override protected void onClose(int status) { InitServlet.getSocketList().remove(this); super.onClose(status); } @Override protected void onOpen(WsOutbound outbound) { super.onOpen(outbound); //Logined in if(name!=null){ InitServlet.getSocketList().put(name, this); } // InitServlet.getSocketList().add(this); } } 4. Message processing class, processing messages sent by the front-end
package util; import java.nio.CharBuffer; import java.util.HashMap; /** * * @ClassName: MessageUtil * @Description: Message processing class* @author mangues * @date -- */ public class MessageUtil { public static HashMap<String,String> getMessage(CharBuffer msg) { HashMap<String,String> map = new HashMap<String,String>(); String m[] = msgString.split(","); map.put("fromName", m[]); map.put("toName", m[]); map.put("content", m[]); return map; } } 5. Web Configuration
<?xml version="1.0" encoding="UTF-8"?><web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <servlet> <servlet-name>mywebsocket</servlet-name> <servlet-class>socket.MyWebSocketServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>mywebsocket</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <servlet> <servlet-name>initServlet</servlet-name> <servlet-class>socket.InitServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app>
6. Front-end, for convenience, I directly used two jsp, and used <%session.setAttribute("user","Xiao Ming")%> to indicate login.
There is no essential difference between the two jsp, it is just used to indicate that two different people are logged in. You can open different jsp in the same browser to chat.
A. Minimize
<%@ page language="java" contentType="text/html; charset=UTF-" pageEncoding="UTF-"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-"> <title>Index</title> <script type="text/javascript" src="js/jquery ...min.js"></script> <%session.setAttribute("user", "minimize");%> <script type="text/javascript"> var ws = null; function startWebSocket() { if ('WebSocket' in window) ws = new WebSocket("ws://localhost:/webSocket/mywebsocket.do"); else if ('MozWebSocket' in window) ws = new MozWebSocket("ws://localhost:/webSocket/mywebsocket.do"); else alert("not support"); ws.onmessage = function(evt) { //alert(evt.data); console.log(evt); $("#xiaoxi").val(evt.data); }; ws.onclose = function(evt) { //alert("close"); document.getElementById('denglu').innerHTML="offline"; }; ws.onopen = function(evt) { //alert("open"); document.getElementById('denglu').innerHTML="online"; document.getElementById('userName').innerHTML='Minimize'; }; } function sendMsg() { var fromName = "Minimize"; var toName = document.getElementById('name').value; //Send to whom var content = document.getElementById('writeMsg').value; //Send content ws.send(fromName+","+toName+","+content); } </script> </head> <body onload="startWebSocket();"> <p>Chat function implementation</p> Login status: <span id="denglu" style="color:red;">Log in</span> <br> Login person: <span id="userName"></span> <br> <br> <br> Who to send to: <input type="text" id="name" value="Xiao Ming"></input> <br> Send content: <input type="text" id="writeMsg"></input> <br> Chat box: <textarea rows="" cols="" readonly id="xiaoxi"></textarea> <br> <input type="button" value="send" onclick="sendMsg()"></input> </body> </html> B. Xiao Ming
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Index</title><script type="text/javascript" src="js/jquery 2.1.1.min.js"></script><%session.setAttribute("user", "Xiao Ming");%><script type="text/javascript">var ws = null;function startWebSocket() { if ('WebSocket' in window) ws = new WebSocket("ws://localhost:8080/webSocket/mywebsocket.do"); else if ('MozWebSocket' in window) ws = new MozWebSocket("ws://localhost:8080/webSocket/mywebsocket.do"); else alert("not support"); ws.onmessage = function(evt) { console.log(evt); //alert(evt.data); $("#xiaoxi").val(evt.data); }; ws.onclose = function(evt) { //alert("close"); document.getElementById('denglu').innerHTML="offline"; }; ws.onopen = function(evt) { //alert("open"); document.getElementById('denglu').innerHTML="online"; document.getElementById('userName').innerHTML="Xiao Ming"; };}function sendMsg() { var fromName = "Xiao Ming"; var toName = document.getElementById('name').value; //Send to whom var content = document.getElementById('writeMsg').value; //Send content ws.send(fromName+","+toName+","+content);}</script></head><body onload="startWebSocket();"><p>Chat function implementation</p>Log in login status: <span id="denglu" style="color:red;">Log in</span><br>Log in person: <span id="userName"></span><br><br><br>Send to: <input type="text" id="name" value="minimize"></input><br>Send content: <input type="text" id="writeMsg"></input><br>Chat box: <textarea rows="13" cols="100" readonly id="xiaoxi"></textarea><br><input type="button" value="send" onclick="sendMsg()"></input></body></html>The above is the relevant knowledge about using JavaWeb webSocket to implement simple peer-to-peer chat function example code. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!