First of all, let's make it clear that you need JDK 7, and Tomcat needs to support the WebSocket version.
1.InitServlet
This class is mainly used to initialize the map warehouse which will store the user's identity information in the future, initialize the warehouse with its initialization method, and use its static method getsocketlist to obtain the corresponding user's identity information.
WebSocket, I think Messageinbound used to identify the logged-in person, use it to find the corresponding person, push the message. Each login will produce a messageinbound.
Here's hashmap<string,messageinbound>: String stores the identity information that the user session's login Id,messageinbound storage push requires. The above belongs to the 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<messag
Einbound> ();
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
WebSocket is used to establish a connected servlet, when a connection is made, the userid of the logged-on person is first obtained in the session, and the Mymessageinbound constructor is invoked to pass UserID
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 the connection was established * @author mangues * @date-* * public class Mywe Bsocketservlet extends Websocketservlet {public string getuser (HttpServletRequest request) {String UserName = (S
Tring) request.getsession (). getattribute ("user");
if (username==null) {return null;
return userName;
Return (String) request.getattribute ("User"); @Override protected Streaminbound createwebsocketinbound (String arg, httpservletrequest request) {Sy
Stem.out.println ("##########"); return new Mymessageinbound (This.getuser (request)); }
}
The 3.onOpen method invokes the Initservlet map identity Warehouse,
Put the user UserID and the WebSocket identity information messageinbound that should be logged on to the user (can use UserID to find the identity of the push needs 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 {//user message processed map hashmap<string,string> Messagemap = messageutil.getmessage (msg);
Process message class//Online User collection class map hashmap<string, messageinbound> usermsgmap = Initservlet.getsocketlist (); String fromname = Messagemap.get ("FromName"); The message comes from a human userid String toname = Messagemap. Get ("ToName"); The message is sent to the person's userId//Get the user messageinbound Messageinbound = usermsgmap.get (ToName); Remove Messageinbound if (messageinbound!=null) {//if sent to person for operation Wsoutbound Outbound = Messageinbound.get in warehouse
Wsoutbound (); String content = messagemap.get ("content"); Get message content String msgcontentstring = fromname + "" + content;
Constructs the sent message//sends out the content charbuffer tomsg = Charbuffer.wrap (Msgcontentstring.tochararray ()); Outbound.writetextmessage (TOMSG);
Outbound.flush (); }/* for (Messageinbound messageInbound:InitServlet.getSocketList ()) {Charbuffer buffer = Charbuffer.wrap (M
SG);
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);
The logged-on user registers in the IF (name!=null) {initservlet.getsocketlist (). Put (name, this);
}//Initservlet.getsocketlist (). Add (this); }
}
4. Message processing class, processing the message from 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 msgstring = msg.tostring ();
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> <s Ervlet-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, the front-end, for convenience, I directly used two JSP, in which with <%session.setattribute ("User", "xiaoming")%>; to represent the login.
Two JSP does not have any essential difference, only uses to represent two different people to log in, may open the different JSP with two browsers, to chat the operation
A. Small-format
<%@ page language= "java" contenttype= "text/html; charset=utf-"pageencoding=" utf-"%> <! DOCTYPE html>
b. Xiaoming
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%> <! DOCTYPE html>
The above is a small set to introduce the use of Javaweb websocket to achieve a simple point-to-point chat function of the relevant knowledge of the code, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!