当前位置:网站首页>websocket
websocket
2022-04-23 16:50:00 【Kramer_ one hundred and forty-nine】
Concept
websocket It's a full duplex channel , After establishing the connection, you can send messages in both directions .
Tomcat 7.0.5 After that, I started to support websocket, And implemented websocket standard .Java websocket The application consists of a series of WebSocketEndpoint form . One Endpoint It's a Java object , representative WebSocket End of link , For the server , It can be regarded as dealing with WebSocket Message interface , It's like servlet Handle http equally .( notes : Build a websocket The link will create a new Endpoint object )
There are two ways to define Endpointt:
1、 Inherit javax.websocket.Endpoint Class and implement its methods .
2、 Definition POJO And add @ServerEndpoint annotation
The data transfer
The server accepts data
adopt Session( and http Medium session Different ) add to MessageHandler Message processor to receive messages , When defining by annotation Endpoint when , adopt @OnMessage The annotation specifies the method of accepting the message .
The server pushes data
The message is sent by RemoteEndpoint complete , In fact, it is by Session maintain , According to usage , We can go through Session.getBasicRemote Get synchronization message sending instance , And then call sendXxx() Method can send a message , Can pass Session.getAsyncRemote Get asynchronous message sending instance .
The backend implementation
Inherit Endpoint Realization way
onOpen Method : Automatically call... After the link is established
onClose Method : Link close auto call
onError Method : If there is a problem in the link, automatically call
annotation @ServerEndpoint Realization way ( The main )
@OnClose
@OnOpen
@OnError
Sample code
@ServerEndpoint("/robin")// Followed by the resource path
public class ChatEndPoint{
private static Set<ChatEndPoint> webSocketSet = new HashSet<>();
private Session session;
@OnMessage
public void onMessage(String message,Session session)throws IOException{
//message Is the message sent by the received client ;session
System.out.println("get message"+message);
System.out.println(session);
// Send messages to other users
for(ChatEndPoint chat:webSocketSet){
if(chat!=this){
chat.session.getBasicRemote().setText(message);
}
}
}
@OnOpen
public void onOpen(Session session){
this.session = session;
webSocketSet.add(this);
}
@OnClose
public void onClose(Session session){
}
@OnError
public void onError(Session session,Throwable error){
}
}
be based on websocket Realize chat room ( Back end code )
rely on
webSocket rely on
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
public resource
Message class , client to Server side
@Data
public class Message{
private String toName;
private String message;
}
ResultMessage, Server side to client
@Data
public class ResultMessage{
private boolean isSystem;
private String fromName;
private Object message;// If it is a system message, it is an array
}
MessageUtils, Message tool class
public class MessageUtils {
public static String getMessage(boolean isSystemMessage,String fromName,Object message){
try {
ResultMessage result = new ResultMessage();
result.setSystem(isSystemMessage);
result.setMessage(message);
if (fromName!=null){
result.setFromName(fromName);
}
// Convert a string to json Format string
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(result);
}catch (JsonProcessingException e){
e.printStackTrace();
}
return null;
}
}
The user login
@RestController
public class LoginController {
@RequestMapping("/toLogin")
public Result tologin(@RequestParam("user") String user,@RequestParam("pwd") String pwd, HttpSession session){
Result result = new Result();
if (user.equals(" Zhang San ")&&pwd.equals("123")){
result.setFlag(true);
session.setAttribute("user",user);
}else if (user.equals(" Li Si ")&&pwd.equals("123")){
result.setFlag(true);
session.setAttribute("user",user);
}else if (user.equals("123")&&pwd.equals("123")){
result.setFlag(true);
session.setAttribute("user",user);
}
else if (user.equals(" Wang Wu ")&&pwd.equals("123")){
result.setFlag(true);
session.setAttribute("user",user);
}else {
result.setFlag(false);
result.setMessage(" Login failed ");
}
return result;
}
@RequestMapping("/getUsername")
public String getUsername(HttpSession session){
String username = (String) session.getAttribute("user");
return username;
}
}
Endpoint
@ServerEndpoint(value = "/chat",configurator = GetHttpSessionConfigurator.class)// Note that there
@Component
public class ChatEndpoint {
// Used to store each user's client object ChatEndpoint object
private static Map<String,ChatEndpoint> onlineUsers = new ConcurrentHashMap<>();
// Statement session object , Through the object, you can send a message to the specified user
private Session session;
// Statement HttpSession object , We were HttpSession The user name... Is stored in the object
private HttpSession httpSession;
// Connection is established
@OnOpen
public void onOpen(Session session, EndpointConfig config){
this.session = session;
HttpSession httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
this.httpSession = httpSession;
// Store the login object
String username = (String)httpSession.getAttribute("user");
onlineUsers.put(username,this);
// Push the user name of the current online user to all clients
//1 Get message
String message = MessageUtils.getMessage(true, null, getNames());
//2 Call methods to push system messages
broadcastAllUsers(message);
}
private void broadcastAllUsers(String message){
try {
// Push messages to all clients
Set<String> names = onlineUsers.keySet();
for (String name : names) {
ChatEndpoint chatEndpoint = onlineUsers.get(name);
chatEndpoint.session.getBasicRemote().sendText(message);
}
}catch (Exception e){
e.printStackTrace();
}
}
// Return online user name
private Set<String> getNames(){
return onlineUsers.keySet();
}
// Received a message
@OnMessage
public void onMessage(String message,Session session){
// Convert data into objects
try {
ObjectMapper mapper =new ObjectMapper();
Message mess = mapper.readValue(message, Message.class);
String toName = mess.getToName();
String data = mess.getMessage();
String username = (String) httpSession.getAttribute("user");
String resultMessage = MessageUtils.getMessage(false, username, data);
// send data
onlineUsers.get(toName).session.getBasicRemote().sendText(resultMessage);
} catch (Exception e) {
e.printStackTrace();
}
}
// close
@OnClose
public void onClose(Session session) {
String username = (String) httpSession.getAttribute("user");
// Delete the specified user from the container
onlineUsers.remove(username);
MessageUtils.getMessage(true,null,getNames());
}
}
Configuration class
You need to add a configuration class Spring Will manage .
@Configuration
public class WebSocketConfig {
@Bean
// Inject ServerEndpointExporter bean object , Automatically register using annotations @ServerEndpoint Of bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
other
obtain HttpSession Class
public class GetHttpSessionConfigurator extends ServerEndpointConfig.Configurator {
@Override
public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
// obtain HttpSession object
HttpSession httpSession = (HttpSession) request.getHttpSession();
sec.getUserProperties().put(HttpSession.class.getName(),httpSession);
}
}
版权声明
本文为[Kramer_ one hundred and forty-nine]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231359460626.html
边栏推荐
- Detailed explanation of file operation (2)
- ACL 2022 | DialogVED:用于对话回复生成的预训练隐变量编码-解码模型
- 无线鹅颈麦主播麦手持麦无线麦克风方案应当如何选择
- On the value, breaking and harvest of NFT project
- Esxi encapsulated network card driver
- Dancenn: overview of byte self-developed 100 billion scale file metadata storage system
- Cartoon: what are IAAs, PAAS, SaaS?
- 如何用Redis实现分布式锁?
- PostgreSQL列存与行存
- Solution of garbled code on idea console
猜你喜欢

MySQL master-slave synchronization pit avoidance version tutorial

Use case labeling mechanism of robot framework

Set the color change of interlaced lines in cells in the sail software and the font becomes larger and red when the number is greater than 100

Selenium IDE and XPath installation of chrome plug-in

How magical is the unsafe class used by all major frameworks?

TypeError: set_ figure_ params() got an unexpected keyword argument ‘figsize‘

Deepinv20 installation MariaDB

Zhongang Mining: Fluorite Flotation Process

建站常用软件PhpStudy V8.1图文安装教程(Windows版)超详细

OMNeT学习之新建工程
随机推荐
Differences between MySQL BTREE index and hash index
Detailed explanation of the penetration of network security in the shooting range
An essay on the classical "tear down the wall in thinking"
如何建立 TikTok用户信任并拉动粉丝增长
On the security of key passing and digital signature
Idea of batch manufacturing test data, with source code
vim编辑器的实时操作
Loading order of logback configuration file
UWA Pipeline 功能详解|可视化配置自动测试
众昂矿业:萤石浮选工艺
feign报400处理
RAID磁盘阵列与RAID5的创建
Use if else to judge in sail software - use the title condition to judge
Mock test using postman
PostgreSQL列存与行存
各大框架都在使用的Unsafe类,到底有多神奇?
Gartner 发布新兴技术研究:深入洞悉元宇宙
批量制造测试数据的思路,附源码
MySql主从复制
计组 | 【七 输入/输出系统】知识点与例题