Java与C交互

/**
 * Java与C交互
 * @param param 上送信息
 * @return 返回信息
 */
public static Map<String, String> infExchange(Object param){
	Map<String, String> returnMsg = null;
	
	Socket socket = null;
	DataOutputStream outputStream = null;
	DataInputStream inputStream = null;
	
	String host = null;
	int port = 0;
	try{
		//读取地址及端口号
		host = Global.getConfig("socket.host");
		port = Integer.valueOf(Global.getConfig("socket.port"));
		
		//创建socket
		socket = new Socket(host, port);
		socket.setSoTimeout(20000);//超时时间设置为20s
		
		//对象转化为json
		ObjectMapper mapper = new ObjectMapper();
		String json = mapper.writeValueAsString(param);
		
		//前加4位长度
		String sendMsg = StringUtils.padLeft(String.valueOf(json.getBytes("GBK").length), '0', 4) + json;
		System.out.println("上送报文:" + sendMsg);
		
		//上送
		outputStream = new DataOutputStream(socket.getOutputStream());
		outputStream.write(sendMsg.getBytes("GBK"));
		outputStream.flush();
		
		//接收返回
		inputStream = new DataInputStream(socket.getInputStream());
		byte[] b = new byte[4];
		int count = 1;//只读取两次,第一次读取报文长度,第二次读取完整报文
		while(inputStream.read(b)!=-1){
			if(count==1){
				int len = Integer.valueOf(new String(b));
				b = new byte[len];
				count++;
				Thread.sleep(200);
			}else{
				break;
			}
		}
		String response = new String(b, "GBK");
		System.out.println("返回报文:" + response);
		
		//将返回json转化为map格式
		if(response!=null && !"".equals(response)){
			returnMsg = mapper.readValue(response, Map.class);
		}
	}catch(Exception e){
		e.printStackTrace();
	}finally{
		//关闭流
		try {
			inputStream.close();
			outputStream.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	return returnMsg;
}

 

posted @ 2016-06-28 12:00  yl_fighting  阅读(775)  评论(0编辑  收藏  举报