package com.telpo.dipperposition.common; import lombok.extern.slf4j.Slf4j; import java.io.*; import java.net.Socket; import java.nio.charset.StandardCharsets; /** * @program: dipperposition * @description: socket连接单元 * @author: king * @create: 2021-01-14 13:52 **/ @Slf4j public class SocketClient { //定义一个Socket对象 Socket socket = null; public SocketClient(String host, int port, int timeout) { try { //需要服务器的IP地址和端口号,才能获得正确的Socket对象 socket = new Socket(host, port); socket.setSoTimeout(timeout); } catch (IOException e) { log.error("Socket Connect Error:" + e.getMessage()); } } public String getOutput() { try { OutputStream os = socket.getOutputStream(); return os.toString(); } catch (IOException e) { log.error("Socket getOutputStream Error:" + e.getMessage()); return null; } } public byte[] sendCmd(String astCmd, String ackAckCheckRef) { try { OutputStream os=socket.getOutputStream(); PrintWriter pw=new PrintWriter(os); // TODO 发生命令 //String info="用户名:Tom,用户密码:123456"; pw.write(astCmd); pw.flush(); socket.shutdownOutput(); //接收服务器的相应 String reply=null; //输入流 InputStream is=socket.getInputStream(); //BufferedReader br=new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)); ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); byte[] buff = new byte[100]; //StringBuffer ackResultBuf= new StringBuffer(); //String ackHexOut = HexConvert.convertStringToHex(ackAckCheckRef); // reply=br.readLine(); // while(reply!=null){ // //log.debug("接收服务器的信息:"+reply); // //if (ackHexOut.equals(reply)) { // ackResultBuf.append(reply); // reply=br.readLine(); // // break; // //} // } int rc = 0; while ((rc = is.read(buff, 0, 100)) > 0) { swapStream.write(buff, 0, rc); } byte[] in2b = swapStream.toByteArray(); //String ackResult = HexConvert.convertHexToString(ackResultBuf.toString()); //4.关闭资源 swapStream.close(); is.close(); pw.close(); os.close(); //log.debug(ackResult); log.debug("接收服务器的信息:"+HexConvert.BinaryToHexString(in2b)); //return HexConvert.BinaryToHexString(in2b); return in2b; } catch (IOException e) { log.error("Socket sendCmd Error:" + e.getMessage()); return null; } } public void closeConnection() { try { socket.close(); //socket.shutdownOutput(); } catch (IOException e) { log.error("Socket getOutputStream Error:" + e.getMessage()); } } }