Javaweb and WebSocket to realize online chat function summary

Source: Internet
Author: User
Tags sendmsg what debugging

Technology from the beginning of the Ajax poll later changed to the handling of some of the problems encountered by WebSocket:

WebSocket Pom-dependent

<dependency>            <groupId>org.springframework</groupId>            <artifactId> spring-websocket</artifactid>            <version>4.0.5.RELEASE</version>        </dependency>

The first is to configure the processor

import Javax.annotation.resource;import Org.springframework.stereotype.component;import Org.springframework.web.servlet.config.annotation.webmvcconfigureradapter;import Org.springframework.web.socket.config.annotation.enablewebsocket;import Org.springframework.web.socket.config.annotation.websocketconfigurer;import org.springframework.web.socket.config.annotation.websockethandlerregistry;/** * Webscoket Configuration Processor * @author Goofy * @ Date June 11, 2015 PM 1:15:09 */@Component @enablewebsocketpublic class Websocketconfig extends Webmvcconfigureradapter Implements Websocketconfigurer {@ResourceMyWebSocketHandler handler;public void registerwebsockethandlers ( Websockethandlerregistry registry) {Registry.addhandler (handler, "/ws"). Addinterceptors (New Handshake ()); Registry.addhandler (Handler, "/ws/sockjs"). Addinterceptors (New Handshake ()). WITHSOCKJS ();}} 

2. The handshake interceptor passed by the request is mainly used to store the user information of the session in the ServerHTTPRequest in attributes to the handle in the processing will be automatically deposited in websocketsession attribute.

Import Java.util.map;import Javax.servlet.http.httpsession;import Org.springframework.http.server.serverhttprequest;import Org.springframework.http.server.ServerHttpResponse; Import Org.springframework.http.server.servletserverhttprequest;import Org.springframework.web.socket.websockethandler;import org.springframework.web.socket.server.handshakeinterceptor;/** * Socket Establish connection (handshake) and disconnect * * @author Goofy * @Date June 11, 2015 PM 2:23:09 */public Class Handshake implements Handshakeinterceptor {public boolean beforehandshake (serverhttprequest Request, serverhttpresponse response, Websockethandler Wshandler, map<string, object> attributes) throws Exception {System.out.println ("Websocket: User [ID:" + (servletserverhttprequest) request). Getservletrequest (). GetSession (False). getattribute ("UID") + "] has established a connection"); if (Request instanceof Servletserverhttprequest) { Servletserverhttprequest ServletRequest = (servletserverhttprequest) request; HttpSession session = Servletrequest.getservletrequest (). GetsessiOn (false);//Mark user Long uid = (Long) session.getattribute ("UID"), if (uid!=null) {attributes.put ("UID", UID);} Else{return false;}} return true;} public void Afterhandshake (ServerHTTPRequest request, serverhttpresponse response, Websockethandler Wshandler, Exception Exception) {}}

Socket processor handles connection communication or error shutdown, etc.

Import Java.io.ioexception;import java.text.simpledateformat;import Java.util.date;import Java.util.HashMap;import Java.util.iterator;import Java.util.map;import Java.util.map.entry;import Org.springframework.stereotype.component;import Org.springframework.web.socket.closestatus;import Org.springframework.web.socket.textmessage;import Org.springframework.web.socket.websockethandler;import Org.springframework.web.socket.websocketmessage;import Org.springframework.web.socket.websocketsession;import Org.xdemo.example.websocket.entity.message;import Com.google.gson.gson;import com.google.gson.GsonBuilder;/** * Socket Processor * * @author Goofy * @Date June 11, 2015 PM 1:19:50 */@Componentpublic class Mywebsockethandler implements WebSocket Handler {public static final Map<long, websocketsession> usersocketsessionmap;static {usersocketsessionmap = new Hashmap<long, websocketsession> ();} /** * */public void afterconnectionestablished (websocketsession session) after connection established throws Exception {Long uid = (Long) session.getattributes (). Get ("UID"), if (Usersocketsessionmap.get (UID) = = null) {Usersocketsessionmap.put (UID , session);}} /** * Message processing, the message sent by the client via the WebSocket API will pass through here and then processed accordingly */public void Handlemessage (websocketsession session, Websocketmessage<?> message) throws Exception {if (Message.getpayloadlength () ==0) return; Message msg=new Gson (). Fromjson (Message.getpayload (). toString (), message.class); Msg.setdate (new Date ()); Sendmessagetouser (Msg.getto (), New TextMessage (New Gsonbuilder (). Setdateformat ("Yyyy-mm-dd HH:mm:ss"). Create (). ToJson (msg)));} /** * Message transfer error handling */public void Handletransporterror (websocketsession session,throwable exception) throws exception {if (SES Sion.isopen ()) {session.close ();} Iterator<entry<long, websocketsession>> it = Usersocketsessionmap.entryset (). Iterator ();// Remove the socket session while (It.hasnext ()) {entry<long, websocketsession> Entry = It.next (), if (Entry.getvalue (). GetId (). Equals (Session.getid ())) {Usersocketsessionmap.remove (Entry.getkey ()); SYSTEM.OUT.PRINTLN ("Socket session has been removed: User ID" + entry.getkey ()); /** * closed after connection */public void afterconnectionclosed (websocketsession session,closestatus closestatus) throws Exception { System.out.println ("Websocket:" + session.getid () + "closed"); Iterator<entry<long, websocketsession>> it = Usersocketsessionmap.entryset (). iterator ();//Remove Socket session while (It.hasnext ()) {Entry<long, websocketsession> Entry = It.next (), if (Entry.getvalue (). GetId (). Equals (Session.getid ())) {Usersocketsessionmap.remove (Entry.getkey ( )); SYSTEM.OUT.PRINTLN ("Socket session has been removed: User ID" + entry.getkey ()); public Boolean supportspartialmessages () {return false;} /** * Send messages to all online users * * @param message * @throws ioexception */public void Broadcast (final textmessage message) throws Ioex ception {Iterator<entry<long, websocketsession>> it = Usersocketsessionmap.entryset (). Iterator ();// Multi-threaded bulk while (It.hasnext ()) {final Entry<long, websocketsession> Entry = It.next (), if (Entry.getvalue (). IsOpen () {//Entry.getvalue (). SendMessage (message); new Thread (New Runnable () {public void run () {try {if (Entry.getvalue (). IsOpen ()) {Entry.getvalue (). SendMessage (message);}} catch (IOException e) {e.printstacktrace ();}}}). Start ();}}} /** * Send a message to a user * * @param userName * @param message * @throws ioexception */public void Sendmessagetouser (Long uid, Text Message message) throws IOException {websocketsession session = Usersocketsessionmap.get (UID); if (session! = NULL && Amp Session.isopen ()) {session.sendmessage (message);}}}

Page

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%><%string path = Request.getcontextpath () ; String basepath = request.getservername () + ":" + request.getserverport () + path + "/"; String basePath2 = request.getscheme () + "://" + request.getservername () + ":" + request.getserverport () + path + "/";%>& lt;! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01//en" "HTTP://WWW.W3.ORG/TR/HTML4/STRICT.DTD" >

  

Some of the problems encountered and the idea of dealing with

1. Before the request in the interceptor is not in the session using the Get method passed in from the page to get the parameter UID (later did not change what debugging when found can get session)

2. Customer service to prevent multiple landing processing:

Get Loginusermap each time you log in if there is no new update for the user and then replace the map into the session
Login Interceptor Verify that the logged in user's SessionID and map are consistent inconsistent instructions are squeezed to re-jump
Loginusermap.put (User.getfid (), sessionId);
Request.getsession (). Getservletcontext (). SetAttribute ("Loginusermap", Loginusermap);

3.

button embedded on the right side of the toolbar click Pin to pop up only one chat page
var op;
OP = window.open ("${webroot}customerchat.json", "newWin1");
Op.focus ();

4.

Compatible with iOS (look at the sec-websocket-extensions inconsistencies in the request header the idea of a change of head result is available)
if (Request.getheaders (). Get ("Sec-websocket-extensions"). Contains ("X-webkit-deflate-frame")) {
list<string> list = new arraylist<string> ();
List.add ("Permessage-deflate");
Request.getheaders (). Remove ("sec-websocket-extensions");
Request.getheaders (). Put ("sec-websocket-extensions", list);
}

Compatible with Nginx
Upstream tjxm.com{
Server 127.0.0.1:8080;
}
server {
Listen 80;
server_name localhost;
Location/{
Proxy_pass http://tjxm.com/;
Proxy_http_version 1.1;
Proxy_set_header Upgrade $http _upgrade;
Proxy_set_header Connection "Upgrade";
}
}

haha first blog a little dish chicken websokcet part is also from the Internet to find the demo

Javaweb and WebSocket to realize online chat function summary

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.