HTML5 WebSocket implements the sample code for point-to-point chat, html5websocket
Yesterday, I used HTML5 websocket to chat with many people in Tomcat. That is the simplest and most basic, and the most important thing is the development environment. We need to meet the requirements of JDK 1.7 and Tomcat 8. Of course, we can also use tom7 7.063!
Today is the last day of the National Day. We work overtime to continue code! Fortunately, I used google to find a point-to-point chat about websocket. What's better is that it can work well with most systems.
Because it is simulated, here we provide two JSP pages A and B, which respectively put two names in the session: small and small. Note that the session here is HttpSession, in previous chats, the session was javax. websocket. session; different.
Let's take a look at the advantages of using HttpSession session to control chat users ~~~
Annotations are not used here. The traditional web. xml configuration method first calls the InitServlet method when the system starts.
Public class InitServlet extends HttpServlet {private static final long serialVersionUID =-inline; 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 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-name> websocket </servlet-name> <servlet-class> socket. myWebSocketServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name> websocket </servlet-name> <u Rl-pattern> *. do </url-pattern> </servlet-mapping> <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 of sending requests at the front-end, like the back-end, and is easily embedded in 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) {su Per (); this. name = name ;}@ Override protected void onBinaryMessage (ByteBuffer arg0) throws IOException {}@ Override protected void onTextMessage (CharBuffer msg) throws IOException {// map HashMap <String, String> messageMap = MessageUtil after the user sends a message. getMessage (msg); // message processing class // map HashMap <String, MessageInbound> userMsgMap = InitServlet. getSocketList (); String fromName = messageMap. get ("fromNa Me "); // The userId String toName = messageMap of the message. get ("toName"); // The userId to which the message is sent // obtain the user MessageInbound messageInbound = userMsgMap. get (toName); // retrieve the MessageInbound messageFromInbound = userMsgMap from the repository. get (fromName); if (messageInbound! = Null & messageFromInbound! = Null) {// If the sender has an operation WsOutbound outbound = messageInbound. getWsOutbound (); WsOutbound outFromBound = messageFromInbound. getWsOutbound (); String content = messageMap. get ("content"); // get the message content String msgContentString = fromName + "said:" + content; // construct the sent message // 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 Login User registers in if (name! = Null) {InitServlet. getSocketList (). put (name, this); // store the customer service ID and user }}@ Override public int getReadTimeout () {return 0 ;}}
Process the information sent from the front end 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-end should also transmit information in the specified format.
<% @ Page language = "java" contentType = "text/html; charset = UTF-8" pageEncoding = "UTF-8" %> <! DOCTYPE html>
This is A. jsp page, and B is the same as above
Through the above code, you can implement a point-to-point chat function. If you do a large job, you can create a web chat system, including chat rooms and single-person chats, it is said that websocket does not support binary transmission, but this is what a large stream says.
However, it seems that binary is not of great significance. I have been confused for a long time. I have said that JavaScript does not support binary. I found that it is only a pile of goods that I did not study .. (Filereader is used)
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.