天天看點

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();
    }
}      

繼續閱讀