HTML5WebSocket implements point-to-point chat

Source: Internet
Author: User
Tags sendmsg

HTML5WebSocket implements point-to-point chat

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 =-3163557381361759907L; private static HashMap
  
   
SocketList; public void init (ServletConfig config) throws ServletException {InitServlet. socketList = new HashMap
   
    
(); Super. init (config); System. out. println (initialize the chat container);} public static HashMap
    
     
GetSocketList () {return InitServlet. socketList ;}}
    
   
  

Here you can combine with your own system. The corresponding web configuration code is as follows:


  
      
           
    
     
Websocket
            
    
     
Socket. MyWebSocketServlet
        
       
           
    
     
Websocket
            
    
     
*. Do
        
       
           
    
     
InitServlet
            
    
     
Socket. InitServlet
            
    
     
1
    
        
       
           
    
     
Index. jsp
        
   
  

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) + logon); 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 {// map HashMap after the user sends the message
  
   
MessageMap = MessageUtil. getMessage (msg); // message processing class // map HashMap of the online user collection class
   
    
UserMsgMap = InitServlet. getSocketList (); String fromName = messageMap. get (fromName); // 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 + Description: + content; // construct the sent message // CharBuffer toMsg = CharBuffer. wrap (msgContentString. toCharArray (); CharBuffer fromMsg = CharBuffer. wrap (msgContentString. toCharArray (); outF RomBound. 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
  
    getMessage(CharBuffer msg) {        HashMap
   
     map = new HashMap
    
     ();        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%>
<Script type = text/javascript src = js/jquery-1.7.2.min.js> </script> <% session. setAttribute (user, small); %> <script type = text/javascript> var ws = null; function startWebSocket () {if ('websocket 'in window) ws = new WebSocket (ws: // localhost: 8080/WebSocketUser/websocket. do); else if ('your websocket 'in window) ws = new your websocket (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 +'
';} Ws. onclose = function (evt) {// alert (close); document. getElementById ('deng '). innerHTML = offline;}; ws. onopen = function (evt) {// alert (open); document. getElementById ('deng '). innerHTML = online; document. getElementById ('username '). innerHTML = 'mine' ;};} function sendMsg () {var fromName = minhua; var toName = document. getElementById ('name '). value; // to whom var content = document. getElementById ('writemsg '). value; // send content ws. send (fromName +, + toName +, + content); // Note format} </script>

Chat function implementation

Logon status: logging on
Logon person:


To whom:
Sent content:
Chat box:
 

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)

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.