qq_32640683 2017-08-30 02:33 采纳率: 25%
浏览 1067
已采纳

各位大神帮个忙,socket接收返回数据报“Connection ”

下面是小弟客户端发送接收数据对的代码,总是在读取服务器返回的数据报错“connection reset”:
public class Client {

public static String DoClient(String host, int port, String data) {
    Socket soc = null;
    OutputStream out = null;
    InputStream is = null;
    BufferedReader br = null;
    String info = null;
    try {
        soc = new Socket(host, port);
        out = soc.getOutputStream();
        String length = String.format("%04d", data.length());


        out.write(length.getBytes());
        out.write(data.getBytes());
        out.flush();
        soc.shutdownOutput();
        System.out.println("发送的数据长度为" + length);

        is = soc.getInputStream();
        br = new BufferedReader(new InputStreamReader(is));

        while ((info = br.readLine()) != null) {
            System.out.println("我是客户端,服务器说:" + info);
        }

    } catch (Exception e) {
        e.printStackTrace();

    } finally {
        try {
            br.close();
            is.close();
            out.close();
            if (soc != null) {
                soc.close();

            }
        } catch (IOException e) {

            e.printStackTrace();

        }
    }

    return info;


}

}

之前没写过这种方式的通讯模式,跪求大神给个详细的解决方案!!!

  • 写回答

9条回答

  • weixin_41466551 2017-12-25 01:00
    关注

    引起这个异常的原因有两个:
    一、客户端和服务器端如果一端的Socket被关闭,另一端仍发送数据,发送的第一个数据包引发该异常;
    二、客户端和服务器端一端退出,但退出时并未关闭该连接,另一端如果在从连接中读数据则抛出该异常。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(8条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?