如何在WSO2 ESB中建立TCP连接并调用TCP服务器?
解决WSO2 ESB与TCP服务器连接异常的问题
你的TCP服务器抛出的java.net.SocketException: Software caused connection abort: recv failed异常,主要是由服务器代码的局限性和ESB TCP传输配置缺失两方面导致的,下面一步步帮你解决:
一、修复TCP服务器代码
你的服务器代码存在两个关键问题:
- 只处理一次连接就关闭了
ServerSocket,无法接受后续请求; - 依赖
readLine()读取数据,但WSO2 ESB发送的消息可能不带换行符,导致服务器阻塞等待,最终ESB超时断开连接。
修改后的服务器代码(支持持续监听、自动资源管理、兼容无换行的消息读取):
public class TCPServer { public static void main(String[] args) { try (ServerSocket serverSocket = new ServerSocket(9090)) { System.out.println("Waiting for clients..."); // 循环接受客户端连接 while (true) { try (Socket socket = serverSocket.accept(); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) { System.out.println("New client connected"); out.println("Hello client!"); // 读取所有输入数据直到客户端断开 String clientInput; while ((clientInput = input.readLine()) != null) { System.out.println("Received message: " + clientInput); } System.out.println("Client disconnected"); } catch (Exception e) { System.out.println("Error handling client connection: " + e.getMessage()); } } } catch (Exception e) { System.out.println("Server initialization failed: " + e.getMessage()); } } }
二、配置WSO2 ESB的TCP传输组件
WSO2 ESB默认没有启用TCP传输发送器,需要手动添加配置:
- 打开
<ESB_HOME>/repository/conf/axis2/axis2.xml文件; - 添加TCP传输发送器和接收器配置:
<!-- TCP Transport Sender --> <transportSender name="tcp" class="org.apache.axis2.transport.tcp.TCPTransportSender"/> <!-- TCP Transport Receiver(ESB自身监听TCP请求的端口,与你的服务器端口9090区分开) --> <transportReceiver name="tcp" class="org.apache.axis2.transport.tcp.TCPTransportListener"> <parameter name="port">9091</parameter> </transportReceiver>
- 重启WSO2 ESB使配置生效。
三、修正ESB API的配置
你的API配置中有两个小错误,同时需要补充TCP传输的必要属性:
<api context="/ex" name="ex" xmlns="http://ws.apache.org/ns/synapse"> <resource methods="POST"> <inSequence> <!-- 明确设置消息类型和内容类型 --> <property name="ContentType" scope="axis2" type="STRING" value="text/plain"/> <property name="messageType" scope="axis2" type="STRING" value="text/plain"/> <log level="full"/> <!-- 单向发送模式,不需要等待响应 --> <property name="OUT_ONLY" scope="default" type="STRING" value="true"/> <!-- 正确设置FORCE_SC_ACCEPTED的值为true,返回202 Accepted给Postman --> <property name="FORCE_SC_ACCEPTED" scope="axis2" type="STRING" value="true"/> <send> <endpoint> <address uri="tcp://ipaddress:9090"> <!-- 添加TCP连接超时参数,避免无限等待 --> <parameter name="tcp.connect.timeout">30000</parameter> </address> </endpoint> </send> </inSequence> <outSequence> <send/> </outSequence> <faultSequence> <!-- 添加错误日志便于排查问题 --> <log level="full" category="ERROR"/> <send/> </faultSequence> </resource> </api>
四、验证步骤
- 启动修改后的TCP服务器;
- 重启WSO2 ESB并部署修正后的API;
- 用Postman发送POST请求(Content-Type: text/plain,消息内容"hello")到ESB的API地址;
- 查看TCP服务器控制台,应该能看到"Received message: hello"的输出,同时Postman会收到202 Accepted的响应。
内容的提问来源于stack exchange,提问作者ashok
相关产品推荐
相关产品推荐

