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



  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
Socket.IO 是一种实时通信协议,它可以在客户端和服务器之间建立双向通信的连接,从而实现实时通信。在集成 Socket.IOSpring Boot 时,可以使用 Spring Boot 中的 WebSockets 模块来实现与客户端的实时通信。 以下是集成 Socket.IOSpring Boot 的步骤: 1. 在 pom.xml 文件中添加以下依赖: ``` <dependency> <groupId>com.corundumstudio.socketio</groupId> <artifactId>netty-socketio</artifactId> <version>1.7.17</version> </dependency> ``` 2. 创建一个 SocketConfig 类,用于配置 Socket.IO: ``` @Configuration public class SocketConfig { @Bean public SocketIOServer socketIOServer() { Configuration config = new Configuration(); config.setHostname("localhost"); config.setPort(9092); SocketIOServer server = new SocketIOServer(config); return server; } } ``` 3. 创建一个 SocketController 类,用于处理 Socket.IO 的事件: ``` @Component public class SocketController { @Autowired private SocketIOServer server; @PostConstruct public void init() { server.addEventListener("message", String.class, (client, data, ackSender) -> { System.out.println("Received message: " + data); server.getBroadcastOperations().sendEvent("message", data); }); } } ``` 在上面的示例中,我们使用 @PostConstruct 注解来初始化 Socket.IO 事件监听器,当客户端发送 "message" 事件时,服务器将打印消息并将其广播给所有客户端。 4. 在 Spring Boot 应用程序主类中添加以下代码: ``` @EnableAutoConfiguration @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Autowired private SocketIOServer server; @PreDestroy private void destroy() { server.stop(); } } ``` 在上面的示例中,我们在应用程序启动时自动启动 Socket.IO 服务器,并在应用程序关闭时停止服务器。 现在,您已经成功地将 Socket.IO 集成Spring Boot 中了。您可以使用 Socket.IO 客户端与服务器进行实时通信。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值