天天看点

springboot+websocket

springboot+websocket:

先引入websocket的依赖包

<dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-websocket</artifactId>
       </dependency>      

html:

springboot+websocket
import org.springframework.stereotype.Component;
 
@Component
@ServerEndpoint("/socket")
public class WebSocketUtil {
       // 创建一个线程安全的set集合用来存放每个客户端对应的WebSocketUtil
       private CopyOnWriteArraySet<WebSocketUtil> webSocketSet = new                                       CopyOnWriteArraySet<WebSocketUtil>();
       // 与某个客户端的连接会话,通过它来给客户端发送消息
       private Session session;
      
       @OnOpen
       public void onOpen(Session session) {
              this.session = session;
              webSocketSet.add(this);
              System.out.println("你有新的连接");
       }
      
       @OnClose
       public void onClose() {
              webSocketSet.remove(this);
       }
      
       @OnError
       public void onError(Throwable e) {
              System.out.println("发生了未知错误,服务终止");
              e.printStackTrace();
       }
      
       @OnMessage
       public void onMessage(String message) {
              System.out.println("来自客户端的消息:"+message);
       }
      
       /**
        * 发送单条数据
        * @param message
        * @throws IOException
        */
       public void sendMessage(String message) throws IOException {
              this.session.getBasicRemote().sendText(message);
                            //getbasicRemote().sendText(message):同时发送信息
       }
      
       public void sendAll(String message) {
              for(WebSocketUtil conn: webSocketSet) {
                     try {
                            conn.sendMessage(message);
                     } catch (IOException e) {
                            e.printStackTrace();
                     }
              }
       }
      
       public static void main(String[] args) {
             
       }
}
2.创建ServerEndpointExporter来管理@ServerEndpoint注解生成的对象
----次配置必须要有,否则报404
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}      

继续阅读