1. 程式人生 > >spring boot 下整合netty socket.io

spring boot 下整合netty socket.io

主要參考了  http://blog.csdn.net/gisam/article/details/78550003

在pom.xml 加入依賴

<!-- https://mvnrepository.com/artifact/com.corundumstudio.socketio/netty-socketio -->
		<dependency>
			<groupId>com.corundumstudio.socketio</groupId>
			<artifactId>netty-socketio</artifactId>
			<version>1.7.11</version>
		</dependency>

在程式Application的入口加入socketio啟動程式碼

import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.SpringAnnotationScanner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class BuyLogApplication {

	public static void main(String[] args) {
		SpringApplication.run(BuyLogApplication.class, args);
	}


	@Bean
	public SocketIOServer socketIOServer() {
		com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
		
		String os = System.getProperty("os.name");
		if(os.toLowerCase().startsWith("win")){   //在本地window環境測試時用localhost
			System.out.println("this is  windows");
			config.setHostname("localhost");
		} else {
			config.setHostname("123.123.111.222");   //部署到你的遠端伺服器正式釋出環境時用伺服器公網ip
		}
		config.setPort(9092);

		/*config.setAuthorizationListener(new AuthorizationListener() {//類似過濾器
			@Override
			public boolean isAuthorized(HandshakeData data) {
				//http://localhost:8081?username=test&password=test
				//例如果使用上面的連結進行connect,可以使用如下程式碼獲取使用者密碼資訊,本文不做身份驗證
				// String username = data.getSingleUrlParam("username");
				// String password = data.getSingleUrlParam("password");
				return true;
			}
		});*/


		final SocketIOServer server = new SocketIOServer(config);
		return server;
	}

	@Bean
	public SpringAnnotationScanner springAnnotationScanner(SocketIOServer socketServer) {
		return new SpringAnnotationScanner(socketServer);
	}
}

加入三個類
import com.corundumstudio.socketio.SocketIOServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;


@Component
@Order(value=1)
public class MyCommandLineRunner implements CommandLineRunner {
    private final SocketIOServer server;


    @Autowired
    public MyCommandLineRunner(SocketIOServer server) {
        this.server = server;
    }


    @Override
    public void run(String... args) throws Exception {
        server.start();
        System.out.println("socket.io啟動成功!");
    }
}

class MessageInfo {
    String MsgContent;

    public String getMsgContent() {
        return MsgContent;
    }

    public void setMsgContent(String msgContent) {
        MsgContent = msgContent;
    }
}

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.UUID;


@Component
public class MessageEventHandler {
    public static SocketIOServer socketIoServer;
    static ArrayList<UUID> listClient = new ArrayList<>();
    static final int limitSeconds = 60;

    @Autowired
    public MessageEventHandler(SocketIOServer server) {
        this.socketIoServer = server;
    }

    @OnConnect
    public void onConnect(SocketIOClient client) {
        listClient.add(client.getSessionId());
        System.out.println("客戶端:" + client.getSessionId() + "已連線");
    }

    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        System.out.println("客戶端:" + client.getSessionId() + "斷開連線");
    }


    @OnEvent(value = "messageevent")
    public void onEvent(SocketIOClient client, AckRequest request, MessageInfo data) {
        System.out.println("發來訊息:" + data.getMsgContent());
        socketIoServer.getClient(client.getSessionId()).sendEvent("messageevent", "back data");
    }


    public static void sendBuyLogEvent() {   //這裡就是向客戶端推訊息了
        String dateTime = new DateTime().toString("hh:mm:ss");

        for (UUID clientId : listClient) {
            if (socketIoServer.getClient(clientId) == null) continue;
            socketIoServer.getClient(clientId).sendEvent("enewbuy", dateTime, 1);
        }
    }

後面就是後端通過MessageEventHandler向客戶端推送訊息了

客戶端html

先引用   

<script src="socket.io.js"></script>
js檔案可以去 https://socket.io/  下載

然後寫js訊息收發程式碼

 function initSocket(){
        //var socket = io('http://localhost:9092');  //本地windows測試環境
        var socket = io('遠端伺服器ip:9092'); //正式釋出環境
        socket.on('connect', function () {
            console.log('socket連線成功');
        });

        socket.on('disconnect', function () {
            console.log('socket連線失敗');
        });

        socket.on('enewbuy', function (time, res) {
            //....收到訊息後具體操作
        });
    }