Java按16进制发送和接收TCP指令

import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import org.apache.http.util.TextUtils;

public class TCPSocket{
	public static void main(String args[]){
		String cmdInfor="00 00 00 00 00 06 01 01 00 01 00 20";
		send(cmdInfor);
	}
	public static String send(String cmdInfor){ 
		String strReturn = null;
		try {  
			//要连接的服务端IP地址  
			String host = "192.168.1.2"; 
			//要连接的服务端对应的监听端口  
			int port = 502;   
			//将十六进制的字符串转换成字节数组
			byte[] cmdInfor2 = hexStrToBinaryStr(cmdInfor);
			
			//1.建立客户端socket连接,指定服务器位置及端口  
			Socket clientSocket =new Socket(host,port);  
			
			//2.得到socket读写流  
			OutputStream os=clientSocket.getOutputStream();  
			PrintWriter pw=new PrintWriter(os);  
			//输入流  
			InputStream is=clientSocket.getInputStream();  
			
			//3.利用流按照一定的操作,对socket进行读写操作  
			os.write(cmdInfor2);  
			os.flush();  
			clientSocket.shutdownOutput();  
			
			//接收服务器的响应 
            		int line = 0; 
			byte[] buf = new byte[is.available()];
			
			 //接收收到的数据
           		 while((line=is.read(buf))!=-1){
	           	        //将字节数组转换成十六进制的字符串
	            		strReturn= BinaryToHexString(buf);
           		 }
			//4.关闭资源  
			is.close();  
			pw.close();  
			os.close();  
			clientSocket.close();
		}catch (Exception e){
			e.printStackTrace();
		}
		return strReturn;
	}  
	
	/**
	 * 将十六进制的字符串转换成字节数组
	 *
	 * @param hexString
	 * @return
	 */
	public static byte[] hexStrToBinaryStr(String hexString) {
 
		if (TextUtils.isEmpty(hexString)) {
			return null;
		}
 
		hexString = hexString.replaceAll(" ", "");
 
		int len = hexString.length();
		int index = 0;
 
		byte[] bytes = new byte[len / 2];
 
		while (index < len) {
 
			String sub = hexString.substring(index, index + 2);
 
			bytes[index/2] = (byte)Integer.parseInt(sub,16);
 
			index += 2;
		}
 
 
		return bytes;
	}
	
	/**
	 * 将字节数组转换成十六进制的字符串
	 *
	 * @return
	 */
	public static String BinaryToHexString(byte[] bytes) {
	    String hexStr = "0123456789ABCDEF";
	    String result = "";
	    String hex = "";
	    for (byte b : bytes) {
	        hex = String.valueOf(hexStr.charAt((b & 0xF0) >> 4));
	        hex += String.valueOf(hexStr.charAt(b & 0x0F));
	        result += hex + " ";
	    }
	    return result;
	}
}

  • 7
    点赞
  • 46
    收藏
    觉得还不错? 一键收藏
  • 10
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值