如何在spring boot中创建一个Tcp Connection来接受连接? [英] How to create a Tcp Connection in spring boot to accept connections?
本文介绍了如何在spring boot中创建一个Tcp Connection来接受连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我经历过这 并明白我需要创建一个 TcpReceivingChannelAdapter
来接受连接.但我不知道如何处理.
I have been through this and understood that I need to create a TcpReceivingChannelAdapter
to accept connections.
But I don't know how to proceed with that.
有人可以指导我吗?
推荐答案
见tcp-client-server 示例 使用 XML 配置的一些指针.
See the tcp-client-server sample for some pointers using XML configuration.
用于Java配置;这是一个简单的 Spring Boot 应用程序...
For Java configuration; here's a simple Spring Boot app...
package com.example;
import java.net.Socket;
import javax.net.SocketFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.annotation.Transformer;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.ip.tcp.TcpReceivingChannelAdapter;
import org.springframework.integration.ip.tcp.connection.AbstractServerConnectionFactory;
import org.springframework.integration.ip.tcp.connection.TcpNetServerConnectionFactory;
import org.springframework.integration.transformer.ObjectToStringTransformer;
import org.springframework.messaging.MessageChannel;
@SpringBootApplication
public class So39290834Application {
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext context = SpringApplication.run(So39290834Application.class, args);
Socket socket = SocketFactory.getDefault().createSocket("localhost", 9999);
socket.getOutputStream().write("foo
".getBytes());
socket.close();
Thread.sleep(1000);
context.close();
}
@Bean
public TcpNetServerConnectionFactory cf() {
return new TcpNetServerConnectionFactory(9999);
}
@Bean
public TcpReceivingChannelAdapter inbound(AbstractServerConnectionFactory cf) {
TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter();
adapter.setConnectionFactory(cf);
adapter.setOutputChannel(tcpIn());
return adapter;
}
@Bean
public MessageChannel tcpIn() {
return new DirectChannel();
}
@Transformer(inputChannel = "tcpIn", outputChannel = "serviceChannel")
@Bean
public ObjectToStringTransformer transformer() {
return new ObjectToStringTransformer();
}
@ServiceActivator(inputChannel = "serviceChannel")
public void service(String in) {
System.out.println(in);
}
}
这篇关于如何在spring boot中创建一个Tcp Connection来接受连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文