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) {
            //....收到消息后具体操作
        });
    }



Spring Boot 集成 Netty-Socket.IO 是一种流行的方式,用于构建实时、双向通信的应用,如聊天应用、游戏服务器等。以下是集成的基本步骤: 1. **添加依赖**: - 添加 Spring Boot 的依赖:在你的 `pom.xml` 文件中加入 Spring Boot Web 和 WebSocket 的支持。 ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> ``` - 如果需要使用 Socket.IO,还需要添加 Netty-Socket.IO 的依赖,例如 `socket.io-client` 和 `netty-all` 或者 `netty-codec-http2`。 2. **配置WebSocket**: - 在 `application.properties` 中启用 WebSocket 支持: ```properties server.webSocket.path=/websocket ``` 3. **创建WebSocket处理器**: 创建一个实现了 `TextMessageHandler` 或 `BinaryMessageHandler` 接口的类,处理客户端发来的消息。例如: ```java @Component public class MySocketIOHandler extends TextWebSocketHandler { // 处理接收到的消息逻辑... } ``` 4. **启动WebSocket服务**: - 使用 `@EnableWebSocketMessageBroker` 注解开启WebSocket broker,并指定前缀: ```java @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { // ... 这里可以设置额外的配置,比如用户连接管理 @Override public void configureMessageBroker(MessageBrokerRegistry config) { config.enableSimpleBroker("/topic"); config.setApplicationDestinationPrefixes("/app"); } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/socket.io").withSockJS(); } } ``` 5. **客户端连接和事件处理**: - 客户端使用 JavaScript 的 Socket.IO 库连接到 `/socket.io` 端点,发送和接收消息。 6. **测试整合**: - 启动你的 Spring Boot 应用,然后通过浏览器访问包含 Socket.IO 脚本的页面,测试连接和通信是否正常。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值