java - 接收数据报包时如何修复SocketTimeoutException
问题描述
我正在使用 jsf,如果我想在 bean 中添加配置,它需要以 xml 字符串的形式发送到创建数据的其他模块,但我面临套接字响应的套接字超时问题,我的意思是无法收到回复。
这是我的代码
private void send(Node n) throws ModuleException {
try {
connection = new DatagramSocket();
StringWriter sw = new StringWriter();
Transformer serializer = TransformerFactory.newInstance().newTransformer();
serializer.transform(new DOMSource(n), new StreamResult(sw));
InetAddress host = InetAddress.getByName(LOCAL_HOST);
DatagramPacket request =
new DatagramPacket(sw.toString().getBytes(), sw.toString().length(), host, LOCAL_PORT);
if (log.isDebugEnabled())
log.debug("Sending the request to policy engine :"+sw.toString());
connection.send(request);
if (log.isDebugEnabled())
log.debug("Request sent to policy engine : OK");
connection.setSoTimeout(5000);
byte[] buffer = new byte[1024];
DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
connection.receive(reply);
String replyMessage = new String(reply.getData()).trim();
if (replyMessage.indexOf("code=\"0\"") < 0){
String errStr = "Response rejected the config:"+parseMessage(replyMessage);
if (log.isInfoEnabled())
log.info(errStr);
throw new IOException(errStr);
}
}catch(SocketTimeoutException e){
log.error("Unable to connect to engine", e);
log.error("Unable to connect to engine", e);
throw new ModuleException("policy is busy");
}catch (Exception e){
log.error("Unable to send data toengine", e);
throw new ModuleException("Unable to send the information to the engine");
}finally {if(connection != null) connection.close();}
}
这是根本原因
java.net.SocketTimeoutException: Receive timed out
at java.net.PlainDatagramSocketImpl.receive0(Native Method)
at java.net.PlainDatagramSocketImpl.receive(PlainDatagramSocketImpl.java:145)
at java.net.DatagramSocket.receive(DatagramSocket.java:725)
at com.redshift.mgmt.resource.PolicyEngineConnection.send(PolicyEngineConnection.java:98)
at com.redshift.mgmt.resource.PolicyEngineConnection.send(PolicyEngineConnection.java:67)
at com.redshift.mgmt.module.PolicyEngine.sendNetworkService(PolicyEngine.java:360)
at com.redshift.mgmt.module.PolicyEngine.addNetworkService(PolicyEngine.java:338)
at com.redshift.mgmt.beans.NetworkServiceListBean.saveService(NetworkServiceListBean.java:424)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
请帮助我如何解决此异常
谢谢
解决方案
推荐阅读
- php - 将 MySQL 5.7 MyISAM 导入 MySQL8 InnoDB £ 不再显示
- flutter - 如何在 Flutter/Dart 中处理应用程序卸载?
- json - 为什么 JSON Schema 最大值在 allOf 中不起作用?
- coq - Coq 上实数的琐碎引理
- java - 在遵循 RESTful API 标准的同时,在同一控制器中拥有 getAll、getById 和 getByEmail 的控制器方法
- autodesk-forge - 访问 Forge 网站登录不起作用
- kotlin - 在 Kotlin 中,几乎所有的东西都是一个表达式并且有一个值
- php - 经过身份验证的用户在请求后随机更改
- javascript - 模板字符串 html 中的函数引用
- html - AJAX 添加的选项未在 Firefox 中的选择中显示