HTML5 WebSocket + Tomcat implementation ● real-time chat room for the Web version (single-user + multi-user)

Source: Internet
Author: User
Tags sendmsg string to json

HTML5 WebSocket + Tomcat implementation ● real-time chat room for the Web version (single-user + multi-user)

After work, I returned to my dormitory and spent more than an hour opening the webpage... Actually drunk. For people who do IT, there is no network or the network gets stuck, which is worse than cutting JJ. First, the LZ computer was hacked by someone else. It was a mysql vulnerability. After the library connected to public WiFi, someone else took advantage of the mysql vulnerability and won the prize, the result is that there is another account named piress on the computer. The simplest way is to make the password more complex, not 'root' or '123 '! Then we re-installed a new system, with more than a dozen devices in the dormitory using one wifi at the same time. In the case of the network, we can make up our brains!

The above is an out-of-the-box remark. After the previous single-person chat was implemented, the single-person chat (point-to-point) and multi-person chat were merged and optimized today, and used as a web chat room, as shown below:

First enter login. on the jsp page, enter your nickname and log on to chat. on the jsp page, I opened four pages to simulate four users, and put the user name in the session to facilitate operations in the background. Of course, you can place the user ID according to the system requirements.

<%@ 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> <% String name = request. getParameter (username); session. setAttribute (user, name); %> <script type = text/javascript> var self = <% = name %>; 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) {var data = evt. data; var obj = eval ('+ data +'); // convert the string to JSON if (obj. type = 'message') {setMessageInnerHTML (obj. data);} else if (obj. type = 'user') {var userArry = obj. data. split (','); $ (# userlist ). empty (); $ (# userlist ). append ( All); $. Each (userArry, function (n, value) {if (value! = Self & value! = 'Admin') {$ (# userlist). append (' '+ Value +'') ;}}) ;}}; Ws. onclose = function (evt) {response ('{denglu'{.html (offline) ;}; ws. onopen = function (evt) {response (online); Response ('your username'your .html (self) ;};} function setMessageInnerHTML (innerHTML) {var temp = parameter ('your message'your .html (); temp + = innerHTML +'
'{}('{Message'}.html (temp);} function sendMsg () {var fromName = self; var toName = $ (# userlist ). val (); // to whom var content =$ (# writeMsg ). val (); // send content ws. send (fromName +, + toName +, + content) ;}</script> WebIM logon status: logging on
Nickname:

To: * Select a chat object
Sent content:
Chat box:

The style is rough, and there is no time spent on the interface. It is not much different from the previous point-to-point communication. The main difference is the onMessage, which determines the message type based on the messages pushed in the background, if the value is 'user', it indicates that a new user is logged on. In this case, the option in the select statement must be updated. The result is that the number of users online is the number of user options, of course, not yourself! If the type is 'message', it is a common message type.

The main change to the background code is the MyMessageInbound file. The Code is as follows:

Package socket; import java. io. IOException; import java. nio. byteBuffer; import java. nio. charBuffer; import java. util. hashMap; import java. util. iterator; import java. util. map; import java. util. set; 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) {HashMap
 
  
MessageMap = MessageUtil. getMessage (msg); // message processing class String fromName = messageMap. get (fromName); // The userIdString toName = messageMap of the message. get (toName); // userIdString mapContent = messageMap. get (content); if (all. equals (toName) {String msgContentString = fromName +: + mapContent; // construct the sent message String content = MessageUtil. sendContent (MessageUtil. MESSAGE, msgContentString); broadcastAll (content);} else {try {singleChat (fromName, toName, mapContent);} catch (IOException e) {e. printStackTrace () ;}} private void singleChat (String fromName, String toName, String mapContent) throws IOException {HashMap
  
   
UserMsgMap = InitServlet. getSocketList (); MessageInbound messageInbound = userMsgMap. get (toName); // retrieve the MessageInboundMessageInbound 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 msgContentString = fromName + + + toName +: + mapContent; // construct the sent message String contentTemp = MessageUtil. sendContent (MessageUtil. MESSAGE, msgContentString); outFromBound. writeTextMessage (CharBuffer. wrap (contentTemp. toCharArray (); outbound. writeTextMessage (CharB Uffer. wrap (contentTemp. toCharArray (); // outFromBound. flush (); outbound. flush ();} else {String content = MessageUtil. sendContent (MessageUtil. MESSAGE, the customer service is not online, please leave a MESSAGE ...); broadcastAll (content) ;}@override protected void onClose (int status) {if (name! = Null) {InitServlet. getSocketList (). remove (name); // Delete the customer service ID and user System. out. println (User + name + exit);} String names = getNames (); String content = MessageUtil. sendContent (MessageUtil. USER, names); broadcastAll (content); super. onClose (status) ;}@ Overrideprotected void onOpen (WsOutbound outbound) {super. onOpen (outbound); if (name! = Null) {InitServlet. getSocketList (). put (name, this); // store the customer service ID and user} String names = getNames (); String content = MessageUtil. sendContent (MessageUtil. USER, names); broadcastAll (content);} private String getNames () {Map
   
    
ExitUser = InitServlet. getSocketList (); Iterator
    
     
It = exitUser. keySet (). iterator (); String names =; while (it. hasNext () {String key = it. next (); names + = key +,;} String namesTemp = names. substring (0, names. length ()-1); return namesTemp;} public static void broadcastAll (String message) {Set
     
      
> Set = InitServlet. getSocketList (). entrySet (); WsOutbound outbound = null; for (Map. Entry
      
        MessageInbound: set) {try {outbound = messageInbound. getValue (). getWsOutbound (); outbound. writeTextMessage (CharBuffer. wrap (message); outbound. flush ();} catch (Exception e) {e. printStackTrace () ;}}@ Overridepublic int getReadTimeout () {return 0 ;}}
      
     
    
   
  
 

The changes are also relatively large, mainly in onOpen. After a user successfully logs on to the console, add a map and push the user list to the foreground as a message. The message type is "user ", the front-end will automatically update the user name to the select on each user chat page.

After a user successfully logs on, the name (id) and the corresponding MyMessageInbound object are stored in the map. As long as the user finds the fromName and toName, the (CHAT) push function can be completed.

By the way, please pay attention to the usage of CharBuffer. wrap (message) as a buffer information usage. It will be cleared once it is used!

The usage here is based on annotation, and the benefits are also pointed out in the previous blog, but now Tomcat 8 is annotated, and our system runs under Tomcat 8, so, we also need to make the Tomcat 8 version.

The Code has been uploaded to the source code for download. In fact, my functions are based on a user in the communication group using socket. I made a function in the system and asked him for information and source code. People were very proud and didn't give anything, so I made it myself. Fortunately, I made it, the effect is exactly the same as that of him!

The technology is to communicate with each other. It is also very good to give some tips!

Okay. It's here today!

 

 

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.