Objective
web开发
It also explains chapter three, which begins with a discussion of knowledge related to front-end communication. Implementation of an online chat room similar to the function or back-end push message to the front, in the absence WebSocket
of the university that the group has been contacted DWR(Direct Web Remoting)
, but also used polling method, when Servlet3.0
it comes out, also use its asynchronous connection mechanism for the front-end communication. Let's talk about it today WebSocket
. It is HTML5
beginning to provide.
- About WebSocket
- Websocker Property
- WebSocket Events
- WebSocket method
- WebSocket Practice
- A little knowledge
- Common Note description
- Build a simple chat room
- Resources
- Summarize
- At last
- Cliché
About WebSocket
WebSocket
is a HTML5
protocol that begins to provide communication on a single TCP
connection 全双工
.
In WebSocket API
, the browser and the server only need to do a handshake action, and then, the browser and the server formed a fast channel. The data can be transmitted to each other directly between the two.
The browser JavaScript
makes WebSocket
a connection request to the server, and after the connection is established, the client and server can TCP
exchange data directly through the connection.
When you get the Web Socket
connection, you can send the data to the server via the send () method and receive the data returned by the server through the onmessage event.
For the front end, create an WebSocket
object that looks like this:
var Socket = new WebSocket(url, [protocol] );
Description: The first parameter URL that specifies the URL of the connection. The second parameter, protocol, is optional and specifies an acceptable sub-protocol.
Websocker Property
The following are WebSocket
the properties of the object. Suppose we used the code above to create an Socket
object:
Properties |
Description |
Socket.readystate |
The read-only property, ReadyState , represents the connection state, which can be the following values: 0-Indicates that the connection has not been established. 1-Indicates that the connection is established and can communicate. 2-Indicates that the connection is shutting down. 3-Indicates that the connection is closed or the connection cannot be opened. |
Socket.bufferedamount |
The read-only property Bufferedamount The number of UTF-8 text bytes that have been sent () in the queue waiting to be transmitted, but not yet emitted. |
WebSocket Events
The following are related events for the WebSocket object. Suppose we used the code above to create the Socket object:
Events |
Event Handlers |
Description |
Open |
Socket.onopen |
Trigger when connection is established |
Message |
Socket.onmessage |
Triggers when the client receives service-side data |
Error |
Socket.onerror |
Trigger when communication error occurs |
Close |
Socket.onclose |
Trigger when connection is closed |
WebSocket method
The following are methods for WebSocket objects. Suppose we used the code above to create the Socket object:
Method |
Description |
Socket.send () |
Send data using a connection |
Socket.close () |
Close connection |
WebSocket Practice
The relevant knowledge points are described in the previous section 浏览器端
webSocket
, and now we are going to build a backend docking application to implement a simple online chat room.
A little knowledge
The backend about WebSocket
implementations are standards-based JSR356
. The advent of the standard, unified
WebSocket
Code notation. The implementation is consistent as long as the Web container support standards are supported JSR356
. And there are two ways of realizing it, one is the 注解
way and the other is inheriting 继承javax.websocket.Endpoint
class.
Common Note description
@WebSocketEndpoint
Annotations are a class-level annotation whose function is to define the current class as a WebSocket server-side. The value of the annotation will be used to listen to the terminal access URL address of the user connection.
@onOpen
When a new connection is opened, the method that is called by this annotation is invoked when there is a new connection.
@onClose
Called when the connection is closed.
@onMessage
The method that is called when the server receives a message sent by the client.
@PathParam
Receive uri
parameter, similar to @pathvariable function, can get corresponding value by URL
Build a simple chat room
0. Join the POM
dependency.
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
1. Write the control layer, corresponding WebSocket
to each event. A common class is extracted at the same time for a common method invocation.
Websocketcontroller.java
/** * WebSocket Simple chat * @author Okong * *///because it is websocket so it is @restcontroller HTTP form//directly replaced by @serverendpoint can, the role is the same is to specify a Address//Indicates a websocket server-side @component@serverendpoint (value = "/my-chat/{usernick}") @Slf4jpublic class Websocketcontroller {/** * Connection event Join NOTE * @param session */@OnOpen public void OnOpen (@PathParam (v Alue = "Usernick") string usernick,session Session) {String message = "There are new visitors [" + Usernick + "] Join the chat room!"; Log.info (message); Websocketutil.addsession (Usernick, session); At this time, all the online notification to a certain login chat room websocketutil.sendmessageforall (message); } @OnClose public void OnClose (@PathParam (value = "Usernick") string usernick,session Session) {string m essage = "Visitor [" + Usernick + "] Exit chat room!"; Log.info (message); Websocketutil.remotesession (Usernick); At this time, all the online notification to a certain login chat room websocketutil.sendmessageforall (message); } @OnMessage public voidOnMessage (@PathParam (value = "Usernick") string Usernick, String message) {//like mass String info = "Visitor [" + Use Rnick + "]:" + message; Log.info (info); Websocketutil.sendmessageforall (message); } @OnError public void OnError (Session session, Throwable Throwable) {log.error ("Exception:", Throwable); try {session.close (); } catch (IOException e) {e.printstacktrace (); } throwable.printstacktrace (); }}
Websocketutil.java
public class Websocketutil {/** * simple use MAP to store online session * */private static final map<string, Sessi on> online_session = new concurrenthashmap<> (); public static void Addsession (String usernick,session Session) {//putifabsent When adding a key-value pair, first determine if the key value pair already exists//does not exist : Add, and return null//presence: No overwrite, return the existing value directly//Online_session.putifabsent (Usernick, SESSION); A simple example does not take into account the complexity of: How simple how come. Online_session.put (Usernick, SESSION); } public static void Remotesession (String usernick) {online_session.remove (Usernick); /** * Send a message to a user * @param session object for a user * @param message * */public static void Sendmes Sage (Session session, String message) {if (session = = null) {return; }//Getasyncremote () and Getbasicremote () asynchronous with synchronous Async async = Session.getasyncremote (); Send Message Async.sendtext (messages); /** * Send messages to all online people * @param messAge */public static void Sendmessageforall (String message) {//jdk8 New method Online_session.foreach (Sess Ionid, session), SendMessage (session, message)); }}
Note the point:
- When you fill in the value of the @ServerEndpoint, you need to add
/
it at the beginning, or the path is invalid.
- You need to add type
@Component
annotations so that they can be scanned.
- Here, and
session
so on, are javax.websocket
under the bag, pay attention to the distinction.
2. Write the main startup class, mainly by adding annotations @EnableWebSocket
and declaring a Websocket endpoint
class.
@SpringBootApplication@EnableWebSocket@Slf4jpublic class Chapter19Application { public static void main(String[] args) { SpringApplication.run(Chapter19Application.class, args); log.info("Chapter19启动!"); } /** * 会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint * 要注意,如果使用独立的servlet容器, * 而不是直接使用springboot的内置容器, * 就不要注入ServerEndpointExporter,因为它将由容器自己提供和管理。 */ @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); }}
3. Launch the application and test with the online test tool. The http://coolaf.com/tool/chattest is used directly here for testing. Of course, you can write one yourself html
.
First, enter our service address: Ws://127.0.0.1:8080/my-chat/okong, after the connection can see the message returned by the server.
We'll open another tab and continue to enter as a different identity:
At this point, you can see the first page opened, also received the message. Now we send a message:
Then, one of the disconnected connections:
Then you can chat happily, a simple chat room is finished.
Resources
- docs.spring.io/spring/docs/4.3.18.release/spring-framework-reference/htmlsingle/#websocket
- docs.spring.io/spring-boot/docs/1.5.15.release/reference/htmlsingle/#boot-features-websockets
- Http://www.oracle.com/technetwork/articles/java/jsr356-1937161.html
- Http://www.runoob.com/html/html5-websocket.html
Summarize
This chapter is mainly about WebSocket
the use of. Because of the existence of a uniform standard, writing webSocket
is also very simple. For a one-to-one chat, you can write your own, because you know the name of the other side, you can find the other side session
and then can send messages.
At last
At present, many big guys on the internet have a SpringBoot
series of tutorials, if there is a similar, please forgive me. This article is the author in front of the computer word knocking, each step is his own practice. If there is something wrong in the text, also hope to put forward, thank you.
Cliché
- Personal QQ:
499452441
- Public Number:
lqdevOps
Personal blog: http://blog.lqdev.cn
Complete Example: github.com/xie19900123/spring-boot-learning/tree/master/chapter-19
Original Address:/HTTP