websocket简单使用(前端及后端)

目录

后端

导入依赖

编写数据载体

编写操作类

配置类

前端(HTML)


使用环境:jdk1.8+maven+springboot

后端

导入依赖

在pom.xml文件的dependencies的标签里引入依赖


            
            org.springframework.boot
            spring-boot-starter-websocket

编写数据载体

消息内容的实体类

import java.io.Serializable;
public class SocketMessage implements Serializable {

    public static String IDENTITY="1";//身份确认
    public static String HEART_BEAT="2";//心跳包
    public static String SEND_MESSAGE="3";//消息
    private static final long serialVersionUID = 4691408250677149975L;
    private String data;
    private String sendUserId;
    private String sendType;

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    public String getSendUserId() {
        return sendUserId;
    }

    public void setSendUserId(String sendUserId) {
        this.sendUserId = sendUserId;
    }

    public String getSendType() {
        return sendType;
    }

    public void setSendType(String sendType) {
        this.sendType = sendType;
    }
}

记录会话的实体类

import javax.websocket.Session;
import java.util.Date;

public class SocketClient {

    private Session session;
    private Date updateTime;

    public SocketClient() {
    }

    public SocketClient(Session session, Date updateTime) {
        this.session = session;
        this.updateTime = updateTime;
    }

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
}

编写操作类

由于通过websocke接收到的消息是字符串类型的消息,我们需要将字符串转为对应的实体类,可以通过gson来进行JSON数据与实体类间的转换(当然用其他的json转实体类的方法也行,我比较喜欢gson)

在pom.xml文件引入gson依赖

        
            com.google.code.gson
            gson
            2.8.5
        

操作类

package com.huzhiming.myapp.base.config.websocket;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * 一个简单的socket
 */
@ServerEndpoint(value = "/mySocket")
@Component
public class SocketConnect {

    /**gson JSON字符串转实体类**/
    public static Gson gson=new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();

    /** 记录当前在线连接数 **/
    public static AtomicInteger onlineCount = new AtomicInteger(0);

    /** 记录在线的客户端 **/
    public static Map clients = new ConcurrentHashMap<>();

    /**
     * 有新的连接
     * @param session
     */
    @OnOpen
    public void onOpen(Session session){
        System.out.println("新增连接");
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message
     * 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        //将消息转换成实体类
        SocketMessage socketMessage =  gson.fromJson(message,SocketMessage.class);

        if(SocketMessage.IDENTITY.equals(socketMessage.getSendType())){
            //身份认证
            SocketClient socketClient = new SocketClient(session,new Date());
            onlineCount.incrementAndGet();
            clients.put(socketMessage.getSendUserId(), socketClient);
        }else if(SocketMessage.HEART_BEAT.equals(socketMessage.getSendType())){
            //心跳包
            SocketClient socketClient = clients.get(socketMessage.getSendUserId());
            if(socketClient !=null){
                socketClient.setUpdateTime(new Date());
            }
        }else if(SocketMessage.SEND_MESSAGE.equals(socketMessage.getSendType())){
            //发送的消息
            if("1".equals(socketMessage.getMessageType())){
                //单发
                SocketClient socketClient = clients.get(socketMessage.getToUser());
                socketClient.getSession().getAsyncRemote().sendText(message);
            }else if("2".equals(socketMessage.getMessageType())){
                //群发
                for (Map.Entry sessionEntry : clients.entrySet()) {
                    SocketClient toSession = sessionEntry.getValue();
                    // 排除掉自己
                    if (!sessionEntry.getKey().equals(socketMessage.getSendUserId())) {
                        toSession.getSession().getAsyncRemote().sendText(message);
                    }
                }
            }
        }
    }


    /**
     * 链接中断时
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("socket错误!");
    }


    /**
     * 手动关闭了连接
     * @param session
     */
    @OnClose
    public void onClose(Session session){
        String userId = "";
        for (Map.Entry sessionEntry : clients.entrySet()) {
            SocketClient toSession = sessionEntry.getValue();
            //根据session id判断是哪个用户关闭了连接
            if(toSession.getSession().getId().equals(session.getId())){
                userId = sessionEntry.getKey();
                break;
            }
        }
        System.out.println("用户离线"+userId);
        //在记录的客户端中移除该用户
        clients.remove(userId);
        onlineCount.decrementAndGet();
    }





}

配置类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class SocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

用于扫描带有@ServerEndpoint的注解,将改类注册为websocket服务

至此后端准备完毕,,运行springboot项目

前端(HTML)

用户id为1,发消息给id为2的用户



	
		
		
	
	




修改一下页面sendObject

用户id为2,给id为1用户发送消息



	
		
		
	
	




websocket简单使用(前端及后端)_第1张图片

websocket简单使用(前端及后端)_第2张图片

一个简单websocket应用就完成啦。

你可能感兴趣的:(websocket,前端,java)