JAVA Socket接口请求方法详解 返回为nul解决方法

Socket接口请求方法详解

package com.engine.common.util;

import org.apache.log4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @author tangyf
 * @project DataHandle
 * @description socket客户端
 **/
public class SocketClient {

	private static final String ENCODE_GBK = "GBK";
	public final static String ENCODE_UTF_8 = "UTF-8";

	public static final int CLIENT_HEAD_LEN = 8;

	private Socket sc = null;
	private String host;
	private int port;

	public SocketClient(String host, int port) {
		this.host = host;
		this.port = port;
	}

	/**
	 *
	 * @param sendMsg
	 * @return
	 * @throws Exception
	 */
	public String sendData(String sendMsg) throws Exception {

		String retStr = "";

		InputStream is = null;
		OutputStream os = null;
		BufferedInputStream bis = null;
		try {
			sc = new Socket(host,port);
			sc.setSoTimeout(300000);

			is = sc.getInputStream();
			os = sc.getOutputStream();

			os.write((sendMsg).getBytes(ENCODE_GBK));
			bis = new BufferedInputStream(is);
			retStr = getReportData(bis);
			
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("连接Socket服务器出错,服务器ip:" + host + ", 端口port:" + port);
		}finally{
			if(is != null) {
				is.close();
			}
			if(os !=null ) {
				os.close();
			}
			if(bis !=null ) {
				bis.close();
			}
		}

		return retStr;

	}
	
	/**
	 * 
	 * 获取响应报文
	 * @return
	 * @throws Exception
	 */
	private String getReportData(BufferedInputStream in) throws Exception
	{
		StringBuilder wenzi=new StringBuilder();        						 //字符串变量接收文件内容
		try{
			byte[] headBytes = new byte[CLIENT_HEAD_LEN];
			logger.info("CLIENT_HEAD_LEN---------------------------------------------{}",CLIENT_HEAD_LEN);
			int temp = in.read(headBytes);
			int dataLength = Integer.parseInt(new String(headBytes, ENCODE_GBK));
			logger.info("dataLength---------------------------------------------{}",dataLength);
			if (temp < CLIENT_HEAD_LEN || dataLength < 1){
				throw new Exception("报文头部信息校验失败:" + new String(headBytes,  ENCODE_GBK));
			}
			byte[] b=new byte[1024];   //byte数组——容器
			int i;                                                   //长度
			while((i=in.read(b))>0){                 //循环读取
				wenzi.append(new String(b,0,i,"GBK"));     //获得文件中的内容 每次返回的内容长度不确定所以循环将内容拼接到一起组成返回的报文,避免出现nul
			}
			logger.info("q请求的报文:{}",wenzi);
		}
		catch (Exception e){
			e.printStackTrace();
			throw new RuntimeException("报文信息截取失败");
		}
		return String.valueOf(wenzi);
	}


}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值