szu_zkjszu_zkj
2021-03-29 20:38
采纳率: 50%
浏览 31
已采纳

java网络编程小问题 求助大佬

题目要求服务器端向客户端发送一个文件 客户端将文件保存并反馈“发送成功”给服务器端 

我的代码如下 为啥没法将文件内容写入到客户端文件夹里 求大佬帮忙 

public class tcptest {
    @Test
    public void client() throws IOException {
        Socket socket=new Socket(InetAddress.getByName("127.0.0.1"),8990);

        InputStreamReader isr=new InputStreamReader(socket.getInputStream());
        BufferedReader br=new BufferedReader(isr);
        FileWriter fw=new FileWriter(new File("ClientData.txt"));


        String str=null;
        char i='1';

        while((str=br.readLine())!=null)
        {
            System.out.println("afhua");
            fw.write("aksnfdas");
            //fw.write(i+" "+str+'\n');
            i++;
        }
        System.out.println("knfkdsanf");

        BufferedOutputStream bos=new BufferedOutputStream(socket.getOutputStream());


        bos.write("接收成功".getBytes());

        fw.close();
        br.close();
        socket.close();
        bos.close();


    }
    @Test
    public void sever() throws IOException {

        ServerSocket ss=new ServerSocket(8990);

        Socket socket=ss.accept();

        OutputStreamWriter osw=new OutputStreamWriter(socket.getOutputStream());
        FileReader fr=new FileReader("SeverData.txt");
        BufferedReader br=new BufferedReader(fr);

          String str;

          while((str=br.readLine())!=null)
          {
              osw.write(str+'\n');
          }

          socket.shutdownOutput();
          BufferedInputStream bis=new BufferedInputStream(socket.getInputStream());
          ByteArrayOutputStream baos=new ByteArrayOutputStream();
          byte[] buffer=new byte[2];
          int len;
          while((len=bis.read(buffer))!=-1)
          {
              baos.write(buffer,0,len);
          }
        System.out.println(baos.toString());

          osw.close();
          br.close();
          socket.close();
          ss.close();
          bis.close();
          baos.close();
    }
}

1条回答 默认 最新

相关推荐 更多相似问题