Replay chat system

After the project is deployed to tomcat container loaded first web.xml file WEB-INF project root directory

<Load-on-startup> 1 </ load-on-startup> Go InitServlet then performed according to the initial configuration

 

Initialization to load the entire project will be the core of a class WebSocketTest

(NATURAL is ① ② to load class byte code words whose initial variables members ③ then perform initMsgQue () method)

(InitServlet in a simple WebSocketTest.initMsgQue (); a process that contains so much content)

 

Notes WebSocketTest class is that it have a lot of articles, and it plays a major role interceptor, first remember

@ServerEndpoint(value = "/websocket",configurator=GetHttpSessionConfigurator.class)

Also intermittent failure to obtain session, atavistic, it should be every action of my websocket the session is not good management.

After a few initial words important static member variables of this class, only one copy in memory

private static Hashtable<Integer, WebSocketTest> connections = new Hashtable<>();

private static QueueCircle msgQue;

private static IMessageSV iMessageSV = MessageSVImp.getInstance();

private static IStaffSV iStaffSV StaffSVImpl.getInstance = ();

 

connections

Look looks and the name to know Hashtable <Integer, WebSocketTest>, each key value stored inside it, it means a connection established with the client

Key: job number, Found: WebSocketTest core object (an object at different times is WebSocketTest multiple copies (a new connection start () when the copy into), then a plurality of different objects in memory WebSocketTest)

(The system, the two most important subject: and the people associated with (left iStaffSV), related to the message (to the right iMessageSV))

(These two classes are a strong operational capacity, then they are the class that implements two interfaces belong to the service layer)

iStaffSV

Provide full life cycle, all live, personnel additions and deletions to change search, leather is so

(It has a static member variable is an instance of this class itself)

(It also has a static factory method is that it returns the static member variables)

(Well, a good understanding of what is generated, it returns this instance there is only a memory, but it is WebSocketTest static member variables iStaffSV cited)

iMessageSV

As such, it provides all the functions related news

It's the same routine and a hair iStaffSV

msgQue

It is called a ring message, is the message queue action

(Watch the chat window, note down which is a real-time online chat system, a message window will scroll in real-time (on display in the message window has bars limit, and it requires real-time broadcast to each client, it is system features we see intuitively))

(This class is nothing static member variables and static methods, instance of it itself as a static member variables of others, it is in memory of a)

Its member variables:

private int size; // should be as long as there is a ring of message queues this thing, I guess

// do not know all of the message queue is cyclic, that is the case, you should have a lock, when it operates to be locked

private final Lock lock = new ReentrantLock();

private MsgNode start, current; // so-called queue, the queue inside there must be an individual right

Its methods:

Constructor (structure, you should tell it to save a few queue on the line)

cover()

remove()

insert()

clear()

display()

getMessages()

getEleNum ()

getSize()

setSize()

getStart()

tart sets ()

getCurrent()

setCurrent()

(Lenovo: it is something that will, one will be fine; synaesthesia: the contents of important things difficult, so that the core of it, just as the message queue, it is very complex, the same source code style like jdk, but this thing a good package, other things were just around the core services Bale)

(MsgQue this member variable initialization is in initMsgQue () This static method is called the outset)

 

(Incidentally, here, said first operation in the configuration file, Constant class)

This class can not only read the configuration file and use, but also can be used to configure some static const

Sao operation:

It loads the code profile, mainly used PropertiesReader, are written in the static {} static block of code inside (inside the need to write a method, one-time key HashMap configuration file is loaded into the whole, and then assigned to a static variable)

 

(Thus, before the browser has access to the project;. After loading the project in tomcat static member variable initialization has been completed)

(Poetry before expressing profound meaning, it must first rich imagery)

Staff

(id,name,code,pwd,headUrl,power,extra,state)

(Code job number, power (S N ordinary ultra-management), extra spare)

StaffToFore (inherited from Staff)

(Foreground when connecting the messageType type, is used to judge speak, or on-line, off the assembly line)

1. Group chat text messages

2. Establish a connection message

3. Close Connect Message

4. The message buffer message

The text message whisper

Message

(id,content,staffId,createdDt,type,targetId,extra)

MessageToFore (inherited from Message)

(staffName,messageType,headUrl)

SharedFile

(id,uploader,createDate,fileType,foreName,backName)

MsgJson

(targetType,message,targetId,type)

 

(After the expiry, when the user visits the project, came to the web.xml , I was told to visit chat.html page)

<body onLoad="startWebSocket()">

First, find the browser server to establish connection websocket (WS This set is a fixed mold)

ws = new WebSocket("ws://"+localhost+"/SmartChat_EAP/websocket");

Of course, before that, go check the cookie , then there is no corresponding content into the LogoutServlet

Into the way

url = "LogoutServlet?reason="+reason;

window.location.href = url;

LogoutServlet rewritten in the cookie (wrote this setPath ( "/ SmartChat_EAP") field, pay attention to this field, go back to change it), and then redirected to the response.sendRedirect ( " login.html ")

Log in login.js function ajaxLogin (username, password) and then request to LoginServlet in check after completion of password update session and cookie, finished back in login.js, to confirm whether the cookie is no problem, no problem and then go to in chat.html (window.location.href = "/SmartChat_EAP/chat.html")

At the moment to go to establish barriers websocket connection, the cookie will not have the

 

Websocket establish connections, go WebSocketTest class, the first to comment (interceptor)

@ServerEndpoint (value = "/websocket",configurator=GetHttpSessionConfigurator.class) treated (where HttpSession httpSession = (HttpSession) request.getHttpSession (); motionless not obtain, intermittent!)

WebSocket connection to 'ws://possible2dream.cn:8080/SmartChat_EAP/websocket' failed: Error during WebSocket handshake: Unexpected response code: 500

Then down into the start () method, the object for the user to establish a connection WebSocketTest (connections.put (this.staff.getId (), this );)

@OnOpen

public void start(Session session, EndpointConfig config)

Prior to this, also check whether login (if you sign in and out of the first connection, and by operating the session, informing the front desk has been top off the (connections.get (stfId) .session.getBasicRemote (). SendText ( " 1 "); changes in this session, the reception ws.onmessage = function (evt) method will receive a response)) start () method, there are three important things: chat member list update and update chat message box and inform other online users to update user list (add or remove this user)

(Static member variables QueueCircle is stored in the current time of the message list, message is the same way to the front of this.session.getBasicRemote () sendText (jsonUtil.toJson (msgs));.)

(Updates member of the class table is taken from the connections; also updates the employee's personal information ((in fact, can be seen here taking a thing from the current object, this is the core classes WebSocketTest, in fact, come to the front desk every time after successful connection request to establish websocket, has been instantiated, but only in the stuffed start () method of the connections)))

(Need to add the process of broadcasting the synchronization lock for connections in synchronized WebSocketTest object)

Process (Start () method performed in multiple passages message to the reception, which are in ws.onmessage = function (evt) responding method (full duplex), and in addition to reception of the received message string in addition, the message is received json and json received message reception is processed in two ways (the array type and the ordinary json json) (and the list contains only two kinds of array: line 4 a message recording list and the member list 2 ))

(This, the server and the client websocket connection has been established completed (browser page is also loaded). To be sure, the time after which the client then communicates with the server, the user object server response is previously established correspondence WebSocketTest of objects, then is to say, some of the methods previously WebSocketTest not mentioned, in fact, are examples of specific WebSocketTest corresponding to the user to use the. (server and client communications in a respective method onMessage accordingly))

 

(= Good beginning is half the battle; but then, Barry is only half of 90!)

Continue to WebSocketTest class introduction to the rest of the method

@OnClose

public void end()

(When disconnected triggers this method, do: Update connections variable, broadcast notification of this person leave)

// Listen for window closing event, when the window is closed, take the initiative to close websocket connected, not disconnected to prevent the connection window is closed, server-side will throw an exception. Before and after the corresponding

window.onbeforeunload = function(){

ws.close();

};

@OnError

public void onError(Throwable t) throws Throwable

(Another method encounters a closer look)

(Time is too precious, ah, I have to go catch the bulk, this also requires repeated more than debugging, Reviewing the Old, to my view of the complex)

 

Small operations

A static member variable of the class, instance of the class is obtained by a static method in another class (static factory method shouted this routine, singleton)

Sentiment

Small wonder partnership skills at the same time, we also understand why the team is to stand out there with big God ah

 

 

Guess you like

Origin www.cnblogs.com/lovesufang/p/12616185.html