【发布时间】:2018-02-28 09:52:39
【问题描述】:
我需要实现一个带有 Spring Integration 的 TCP 客户端,使用注释,没有 xml conf。
TCP 服务器必须发送文件,我必须使用 Spring Integration 来处理它们,并打印它们(现在)。所以,我用python制作了一个TCP服务器,但这并不重要。代码:
import socket as s
host = ''
port = 2303
co = s.socket(s.AF_INET, s.SOCK_STREAM)
co.bind((host, port))
co.listen(5)
print("Server is listening on port {}".format(port))
conn, addr = co.accept()
print('Connected by', addr)
while True:
try:
data = conn.recv(1024)
if not data: break
print("Client Says: " + data)
conn.sendall("Server Says:hi")
except s.error:
print("Error Occured.")
break
print("Closing connection")
conn.close()
对于客户端,这里是使用 spring 集成的代码:
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.ip.tcp.TcpInboundGateway;
import org.springframework.integration.ip.tcp.connection.TcpNetClientConnectionFactory;
import org.springframework.integration.transformer.ObjectToStringTransformer;
import org.springframework.messaging.MessageChannel;
@Configuration
public class TCPInputChannel {
private static final Logger LOGGER = Logger.getLogger(TCPInputChannel.class);
@Bean
TcpNetClientConnectionFactory clientConnectionFactory() {
LOGGER.info("create TcpNetClientConnectionFactory");
TcpNetClientConnectionFactory cf = new TcpNetClientConnectionFactory("localhost", 2303);
cf.setSingleUse(false);
cf.setSoTimeout(10000);
return cf;
}
@Bean
TcpInboundGateway gateway() {
LOGGER.info("create TcpInboundGateway");
TcpInboundGateway g = new TcpInboundGateway();
g.setConnectionFactory(clientConnectionFactory());
g.setClientMode(true);
g.setRetryInterval(1000);
g.setRequestChannel(input());
return g;
}
@Bean
public MessageChannel input() {
return new DirectChannel();
}
@ServiceActivator(inputChannel = "input", outputChannel = "respString")
ObjectToStringTransformer stringTransformer() {
LOGGER.info("create ObjectToStringTransformer");
ObjectToStringTransformer st = new ObjectToStringTransformer();
return st;
}
@ServiceActivator(inputChannel = "respString")
public String receive(String recv) {
LOGGER.info("Recv: " + recv);
return "echo";
}
}
当我运行它时,服务器可以建立连接,但他不能发送消息,并且客户端不打印任何内容。
【问题讨论】:
标签: java python spring tcp spring-integration