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

  

posted @ 2019-06-21 11:32  黑魔法os  阅读(803)  评论(0编辑  收藏  举报