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 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀