如何用代码演示TCP的异常

阅读 2.7k
1 个回答

重现了Connection reset by peer,代码如下

//client
    public static void main(String[] args) {
        try {
            Socket s = new Socket();
            s.setSoLinger(true,0);//设置调用close就发送RST
            s.connect(new InetSocketAddress("127.0.0.1",3113));

            OutputStream os = s.getOutputStream();
            os.write("hello".getBytes());

            s.close();

            System.in.read();//防止程序退出
        }catch (Exception e){
            e.printStackTrace();
        }
    }
//server
        try {
            ServerSocket ss = new ServerSocket(3113);
            Socket s = ss.accept();
            InputStream is = s.getInputStream();
            byte[] buf =new byte[1024];
            //int len = is.read(buf);
            //System.out.println("recv:"+new String(buf,0,len));

            Thread.sleep(10000);

            s.getOutputStream().write("hello".getBytes());

            System.out.println("send over");
            System.in.read();
        }catch (Exception e){
            e.printStackTrace();
        }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏