如何在Spring框架中实现UDP [英] How to implement UDP in Spring framework

查看:23
本文介绍了如何在Spring框架中实现UDP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经用 spring 框架实现了一个 web 应用程序.现在我需要一个 udp 服务器来接收来自客户端(android 设备)的传入消息.如何将此功能添加到基于 spring 的项目中?谢谢.

I have implemented a web app with spring framework. Now I need a udp server that receive incoming messages from clients (android devices). How can I add this functionality into my spring based project? Thanks.

推荐答案

如果你想使用 Spring 的 rel="noreferrer">TCP 和 UDP 支持集成,假设您只收到一条 UDP 消息并对该消息进行处理,您应该按照以下步骤操作:

If you want to use the TCP and UDP Support of Spring Integration, supponing you just receive an UDP message and do something with that message, you should follow the next steps:

package com.example.udp;

import org.springframework.messaging.Message;

public class UDPConsumer {

    @Autowire what you want, this will be a Spring Bean

    @ServiceActivator
    public void consume(Message message) {
         ... do something with message ...
    }
}

可选:使用一些属性创建一个 udp-server.properties

udp-server.threads=10
udp-server.port=4000
udp-server.buffer-size=500
...

创建配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:int="http://www.springframework.org/schema/integration"
    xmlns:int-ip="http://www.springframework.org/schema/integration/ip"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
        http://www.springframework.org/schema/integration/ip http://www.springframework.org/schema/integration/ip/spring-integration-ip.xsd">

    <context:property-placeholder location="classpath:udp-server.properties" />

    <bean id="udpConsumer" class="com.example.udp.UDPConsumer" />

    <int:channel id="inputChannel">
        <int:queue />
    </int:channel>

    <int-ip:udp-inbound-channel-adapter id="udpReceiver"
        channel="inputChannel"
        port="${udp-server.port}"
        pool-size="${udp-server.threads}"
        receive-buffer-size="${udp-server.buffer-size}"
        multicast="false"
        check-length="true"/>

    <int:service-activator input-channel="inputChannel"
        ref="udpConsumer" />

    <int:poller default="true" fixed-rate="500" />

</beans>

注释:Spring Integration 有很多有趣的特性,比如消息路由和转换.我建议准确查看官方文档.

Notes: Spring Integration has a lot of interesting features, like message routing and transformation. I recommend to have an accurate look at the official documentation.

这篇关于如何在Spring框架中实现UDP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆