丨泡泡唐丨 2023-01-13 23:41 采纳率: 100%
浏览 14
已结题

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

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

我使用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);
//            }
//        });
    }

}

​
  • 写回答

2条回答 默认 最新

  • 小小野猪 2023-01-14 00:41
    关注

    client.shutdownOutput();是关闭服务器连接,关闭连接后 在通过输入流读取in.read();就会造成题主说的"获取不到Socket的返回值"的问题。
    按照如下代码块修改即可:

    
    //输出完后,需要关闭socket的输出通道,表示不存向服务端输出内容
    client.shutdownOutput();
    //读取socket的返回值
    int readLen = in.read();
    
    ================================
    这部分代码改为下面的代码:==========
    ================================
    
    
    //读取socket的返回值
    int readLen = in.read();
    
    //输出完后,需要关闭socket的输出通道,表示不存向服务端输出内容
    client.shutdownOutput();
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 2月1日
  • 已采纳回答 1月24日
  • 创建了问题 1月13日

悬赏问题

  • ¥15 echarts动画效果失效的问题。官网下载的例子。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加