Yesterday, I used HTML5 websocket and Tomcat to implement multi-person chat. It is the simplest and most basic. The most important thing to pay attention to is the development environment, which must meet jdk1.7 and tomcat8. Of course, tom7 7.063 will also work!
Today is the last day of National Day, so I have to work overtime and continue to code! Fortunately, I used Google to find peer-to-peer chat about websocket. What’s even better is that it can work well with most systems. Take a look at the renderings.
Because it is simulated, what is given here are two JSP pages A and B, which put two names Xiaoming and Xiaohua into the session respectively. Note that the session here is HttpSession session, and the session in the previous multi-person chat is javax.websocket.Session; is different.
Think about it here, use HttpSession session to control chat users, guess what are the benefits~~~
Annotations are not used here. In the traditional web.xml configuration method, the InitServlet method is first called when the system starts.
public class InitServlet extends HttpServlet { private static final long serialVersionUID = -3163557381361759907L; private static HashMap<String,MessageInbound> socketList; public void init(ServletConfig config) throws ServletException { InitServlet.socketList = new HashMap<String,MessageInbound>(); super.init(config); System.out.println(initialize chat container); } public static HashMap<String,MessageInbound> getSocketList() { return InitServlet.socketList; } }
Here you can combine it with your own system. The corresponding web configuration code is as follows:
<?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>websocket</servlet-name> <servlet-class>socket.MyWebSocketServlet</servlet-class > </servlet> <servlet-mapping> <servlet-name>websocket</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 ><!--Method execution level--> </servlet> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app>
This is the most common process for the front desk to send requests to the background, and it is also easy to embed into your own system.
MyWebSocketServlet:
public class MyWebSocketServlet extends WebSocketServlet { public String getUser(HttpServletRequest request){ String userName = (String) request.getSession().getAttribute(user); if(userName==null){ return null; } return userName; } protected StreamInbound createWebSocketInbound (String arg0, HttpServletRequest request) { System.out.println(user + request.getSession().getAttribute(user) + login); return new MyMessageInbound(this.getUser(request)); }}
MyMessageInbound inherits MessageInbound
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 arg0) throws IOException { } @Override protected void onTextMessage(CharBuffer msg) throws IOException { //The map after processing the message sent by the user HashMap<String,String> messageMap = MessageUtil.getMessage(msg); //Processing message class //Online user collection class map HashMap<String, MessageInbound> userMsgMap = InitServlet.getSocketList(); String fromName = messageMap.get(fromName); //The message comes from the userId of the person String toName = messageMap.get(toName); //The userId of the person to whom the message is sent //Get the user's MessageInbound messageInbound = userMsgMap.get(toName); //Get the MessageInbound sent to the person in the warehouse MessageInbound messageFromInbound = userMsgMap.get(fromName); if(messageInbound!=null && messageFromInbound!=null){ //If the sender exists, perform the operation WsOutbound outbound = messageInbound.getWsOutbound(); WsOutbound outFromBound = messageFromInbound.getWsOutbound(); String content = messageMap.get(content); //Get the message content String msgContentString = fromName + say: + content; //Construct the message to be sent //Send the content CharBuffer toMsg = CharBuffer.wrap(msgContentString .toCharArray()); CharBuffer fromMsg = CharBuffer.wrap(msgContentString.toCharArray()); outFromBound.writeTextMessage(fromMsg); outbound.writeTextMessage(toMsg); // outFromBound.flush(); outbound.flush(); } } @Override protected void onClose(int status) { InitServlet.getSocketList().remove(this) ; super.onClose(status); } @Override protected void onOpen(WsOutbound outbound) { super.onOpen(outbound); //The logged-in user is registered if(name!=null){ InitServlet.getSocketList().put(name, this);//Storage customer service ID and user} } @Override public int getReadTimeout( ) { return 0; } }
Process the information sent by the foreground in onTextMessage and encapsulate the information to the target.
There is also a messageutil
package util;import java.nio.CharBuffer;import java.util.HashMap;public class MessageUtil { public static HashMap<String,String> getMessage(CharBuffer msg) { HashMap<String,String> map = new HashMap<String,String> (); String msgString = msg.toString(); String m[] = msgString.split(,); map.put(fromName, m[0]); map.put(toName, m[1]); map.put(content, m[2]); return map; }}
Of course, the front desk must also transmit information in the prescribed format.
<%@ 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-1.7.2.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:8080/WebSocketUser/websocket.do); else if ('MozWebSocket' in window) ws = new MozWebSocket(ws://localhost:8080/WebSocketUser/websocket.do); else alert(not support); ws.onmessage = function(evt) { //alert(evt.data ); console.log(evt); // $(#xiaoxi).val(evt.data); setMessageInnerHTML(evt.data); }; function setMessageInnerHTML(innerHTML){ document.getElementById('message').innerHTML += innerHTML + '<br/>'; } 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='xiaohua'; };}function sendMsg() { var fromName = xiaoxing; var toName = document.getElementById( 'name').value; //To whom to send var content = document.getElementById('writeMsg').value; //Send content ws.send(fromName+,+toName+,+content);//Pay attention to the format}</script></head><body onload=startWebSocket();><p>Chat function implementation</p> Login Status: <span id=denglu style=color:red;>Logging in</span><br>Login person: <span id=userName></span><br><br><br>To whom: < input type=text id=name value=小明></input><br>Send content: <input type=text id=writeMsg></input><br>Chat box: <div id=message style=height: 250px;width: 280px ;border: 1px solid; overflow: auto;></div><br><input type=button value=send onclick=sendMsg()></input></body></html>
This is the A.jsp page, B is the same as above
Through the above code, a point-to-point chat function can be realized. If it is large-scale, it can be made into a web version of the chat system, including chat rooms and single-person chats. It is said that websocket does not support binary transmission, but I saw a big Liu said something like this
But now I feel that using binary is not very meaningful. I have been confused for a long time. It was said that JS does not support binary. I found that it is actually just a bunch of scammers who have not studied this. . (Using filereader)
The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.