串口转网络调试组手能正常接受到返回数据,但是java的socket获取不到返回值

丨泡泡唐丨 2023-01-13 23:41:22

我使用的有人的串口服务器,调试助手都是的正常的,

我使用java的socket给TCP的服务器发送数据,也是正常的,就是获取不到Socket的返回值

下面是测试的代码

    @Test
    public void test1() throws IOException, InterruptedException {
        //客户端
        String send = SocketTools.send("192.168.0.7", 26, "8A0101119B");
        System.out.println("send = " + send);
    }

下面是工具类

​
package com.applida.util.socket;

import com.applida.util.TjStringUtil;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @author JL
 * @version V1.0
 * @Description 用java.net.Socket进行Socket操作工具类
 */
public class SocketTools {

    /**
     * 发送数据
     *
     * @param host    ip地址
     * @param port    端口
     * @param content 内容
     * @throws IOException
     */
    public static String send(String host, int port, String content) throws IOException {
        Socket client = null;
        String msg;
        InputStream in = null;
        OutputStream out = null;
        if (StringUtils.isEmpty(host) || port == 0 || StringUtils.isEmpty(content)) {
            return null;
        }
        //去除空字符串
        content = content.replace(" ", "");
        try {
            //创建连接
            client = new Socket(host, port);
            //设置超时时间
            client.setSoTimeout(2000);
            //socket返回的数据流
            in = client.getInputStream();
            //socket发送的流(输出流)
            out = client.getOutputStream();
            //content按16进制字符串发送
            out.write(TjStringUtil.hexStrToBytes(content));
            //输出完后,需要关闭socket的输出通道,表示不存向服务端输出内容
            client.shutdownOutput();
            //读取socket的返回值
            int readLen = in.read();
            System.out.println("返回值长度 = " + readLen);
            msg = receive(in);
            return msg;
        } catch (UnknownHostException uhe) {
            uhe.printStackTrace();
            throw new IOException("主机连接创建异常:" + uhe.getMessage());
        } catch (IOException ioe) {
            ioe.printStackTrace();
            throw ioe;
        } finally {
            streamClose(in, out);
            clientClose(client);
        }
    }

    public static void streamClose(InputStream in, OutputStream out) {
        //IOUtils.closeQuietly(in); 可用IOUtils工具类关闭流
        if (in != null) {
            try {
                in.close();
            } catch (IOException ioe) {
                System.out.println("关闭输入流异常:" + ioe.getMessage());
            }
        }
        if (out != null) {
            try {
                out.flush();
                out.close();
            } catch (IOException ioe) {
                System.out.println("关闭输出流异常:" + ioe.getMessage());
            }
        }
    }

    /**
     * 创建一个客户端Socket连接
     *
     * @param host ip地址
     * @param port 端口号
     * @return
     * @throws UnknownHostException
     * @throws IOException
     */
    private static Socket createClientSocket(String host, int port) throws UnknownHostException, IOException {
        return new Socket(host, port);
    }


    private static void clientClose(Socket socket) {
        if (socket != null && !socket.isClosed()) {
            try {
                socket.close();
            } catch (IOException ioe) {
                System.out.println("Socket关闭异常:" + ioe.getMessage());
            }
        }
    }

    /**
     * 发送数据
     *
     * @param out
     * @param content
     * @return
     * @throws IOException
     */
    public static OutputStream output(OutputStream out, String content) throws IOException {
        try {
//            out.write(content.getBytes(ENCODING));
            out.write(TjStringUtil.hexStrToBytes(content));
        } finally {
            return out;
        }
    }

    /**
     * 接受返回的数据
     *
     * @param in
     * @return
     * @throws IOException
     */
    public static String input(InputStream in) throws IOException {
        int len;
        char[] b = new char[1024];
        StringBuilder sb = new StringBuilder();
        BufferedReader reader;
        try {
            //以字符流为主,如需字节流,则不需要BufferedReader和InputStreamReader,可以直接从InputStream中获取或采用对应缓冲包装类
            reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
            while ((len = reader.read(b)) != -1) {
                sb.append(b, 0, len);
            }
            //reader.close();
        } finally {
        }
        return sb.toString();
    }

    /**
     * 接受服务器返回的数据
     *
     * @return 16进制字符串
     */
    public static String receive(InputStream is) {
        try {
            //客户端开始接受请求
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String result = br.readLine();
            System.out.println("result = " + result);
//        byte[] buffer = new byte[128];
//        int data;
//        String result = null;
//        try {
//            int len = 0;
//            while ((data = in.read()) > -1) {
//                buffer[len++] = (byte) data;
//            }
//            byte[] copyValue = new byte[len];
//            System.arraycopy(buffer, 0, copyValue, 0, len);
//            result = TjStringUtil.bytesToString(copyValue);
//            System.out.println("设备->电脑的数据 = " + result);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    public interface SocketFunction {
        /**
         * socket信息回调
         *
         * @param msg
         */
        void callback(String msg);
    }


    public static void main(String[] args) throws IOException, InterruptedException {
        String data = "这是测试数据:";
        String send = send("192.168.0.7", 26, "8A0101119B");
        System.out.println("send = " + send);
        //测试时,请分别单独启动send和listen方法
        //客户端
//        send("192.168.0.7", 26, "8A0101119B", new SocketFunction() {
//            @Override
//            public void callback(String msg) {
//                System.out.println(data + msg);
//            }
//        });
//        System.in.read();

//        //服务端
//        listen(8111, "this is server test", new SocketFunction() {
//            @Override
//            public void callback(String msg) {
//                System.out.println(data + msg);
//            }
//        });
    }

}

​

 

...全文
180 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

2,643

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 硬件/系统
社区管理员
  • 硬件/系统社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧