websocket的使用
Posted qinyios
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了websocket的使用相关的知识,希望对你有一定的参考价值。
import java.io.IOException; import java.net.http.WebSocket; import java.util.concurrent.CopyOnWriteArraySet; import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; import org.springframework.stereotype.Component; import groovy.util.logging.Slf4j; @Component @ServerEndpoint("/mywebsocket") //@Slf4j public class Websocketcontroller private Session session; private static CopyOnWriteArraySet webSocketset=new CopyOnWriteArraySet(); @OnOpen public void onOpen(Session session) this.session=session; webSocketset.add(this); System.out.println(webSocketset.size()); @OnClose public void onClose() webSocketset.remove(this); System.out.println(webSocketset.size()); @OnMessage public void onMessage(String msg) System.out.println("shoudao msg"+msg); public void sendMessage(String msg) String msg1="ok"; for(Object seb:webSocketset) try ((Session) seb).getBasicRemote().sendText(msg1); catch (IOException e) // TODO Auto-generated catch block e.printStackTrace();
package com.example.demo.websocket; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; import org.springframework.web.socket.server.standard.ServerEndpointExporter; @Component public class Websocketconfig @Bean public ServerEndpointExporter serverEndpointExporter() return new ServerEndpointExporter();
以上是关于websocket的使用的主要内容,如果未能解决你的问题,请参考以下文章