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 微带串馈天线阵列每个阵元宽度计算
  • ¥15 关于无人驾驶的航向角
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了