java web服务器接收数据包_java socket 怎么获取设备tcp发送到服务器端口的心跳数据包...

本文主要探讨了在Java Web项目中,使用SocketUtils类尝试从特定设备通过TCP连接接收心跳数据包时遇到的问题。作者在代码中设置连接参数并尝试读取输入流,但遇到了SocketTimeoutException和'400 Bad Request'错误。文章旨在分析问题原因并寻求解决方案。
摘要由CSDN通过智能技术生成

使用百度的socketUtil能连接上,但拿不到数据,不是400就是超时

idea中Javaweb项目写main方法测试

相关代码

public class SocketUtils {

private static Logger logger = Logger.getLogger(SocketUtils.class);

/**

* 发送socket请求

* @param clientIp

* @param clientPort

* @param msg

* @return

*/

public static synchronized String tcpPost(String clientIp,String clientPort,String msg){

String rs = "";

if(clientIp==null||"".equals(clientIp)||clientPort==null||"".equals(clientPort)){

logger.error("Ip或端口不存在...");

return null;

}

int clientPortInt = Integer.parseInt(clientPort);

logger.info("clientIp:"+clientIp+" clientPort:"+clientPort);

Socket s = null;

OutputStream out = null;

InputStream in = null;

try {

s = new Socket(clientIp, clientPortInt);

s.setSendBufferSize(4096);

s.setTcpNoDelay(true);

s.setSoTimeout(60*1000);

s.setKeepAlive(true);

//out = s.getOutputStream();

in = s.getInputStream();

//准备报文msg

//logger.info("准备发送报文:"+msg);

//out.write(msg.getBytes("GBK"));

//out.flush();

byte[] rsByte = readStream(in);

if(rsByte!=null){

rs = new String(rsByte, "GBK");

}

} catch (Exception e) {

logger.error("tcpPost发送请求异常:"+e.getMessage());

}finally{

logger.info("tcpPost(rs):"+rs);

try {

if(out!=null){

out.close();

out = null;

}

if(in!=null){

in.close();

in = null;

}

if(s!=null){

s.close();

s = null;

}

} catch (IOException e) {

e.printStackTrace();

}

}

return rs;

}

/**

* 读取输入流

* @param in

* @return

*/

public static byte[] readStream(InputStream in){

if(in==null){

return null;

}

byte[] b = null;

ByteArrayOutputStream outSteam = null;

try {

byte[] buffer = new byte[1024];

outSteam = new ByteArrayOutputStream();

int len = -1;

while ((len = in.read(buffer)) != -1) {

outSteam.write(buffer, 0, len);

}

b = outSteam.toByteArray();

} catch (IOException e) {

logger.error("读取流信息异常"+e);

e.printStackTrace();

} finally{

try {

if(outSteam!=null){

outSteam.close();

outSteam = null;

}

if(in!=null){

in.close();

in = null;

}

} catch (IOException e) {

e.printStackTrace();

}

}

return b;

}

}

读取流信息异常java.net.SocketTimeoutException: Read timed out或者tcpPost(rs):400 Bad Request然后一段400的html代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值