gpt4 book ai didi

java - 如何在 spring boot 中创建一个 Tcp 连接来接受连接?

转载 作者:可可西里 更新时间:2023-11-01 02:29:45 31 4
gpt4 key购买 nike

我已经通过了this并了解我需要创建一个 TcpReceivingChannelAdapter 来接受连接。但我不知道如何继续。

有人可以指导我吗?

最佳答案

参见 tcp-client-server sample一些使用 XML 配置的指针。

用于Java配置;这是一个简单的 Spring Boot 应用程序...

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\r\n".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);
}

}

关于java - 如何在 spring boot 中创建一个 Tcp 连接来接受连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39290834/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com