⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 downloadingfileserver.java

📁 下载文件服务器说明(使用Socket完成文件的下载的任务
💻 JAVA
字号:
/** * 下载文件服务器 * */package downloadingfile;import java.net.*;import java.io.*;public class DownloadingFileServer{  //声明所需的类的变量  //声明ServerSocket以及Socket  private ServerSocket SSocket = null;  private Socket socket = null;  //读取客户端提交的请求文件名字的流类  BufferedReader BRClient = null;  //指向客户端的输出流  BufferedOutputStream BOSClient = null;  //指向服务器文件的本地流  BufferedInputStream BISServer = null;  public void Service()  {    try    {      SSocket = new ServerSocket(8000);      System.out.println("等待客户端连接...");      socket = SSocket.accept();      System.out.println("客户端已经连接...");      //指向客户端的输入流用来读取客户端提交的文件名      BRClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));      //指向客户端的输出流(注意流链的写法)      BOSClient = new BufferedOutputStream(socket.getOutputStream());      //读取客户端所需的文件的名字      String fileName = BRClient.readLine();      //指向服务器本地的文件名,此时文件如果不存在则抛出异常。      BISServer = new BufferedInputStream(new FileInputStream(fileName));      //如果文件存在向客户端给出准备完成的信号      BOSClient.write("000".getBytes());      BOSClient.flush();      //读取文件的内容发送给客户端      byte[] byte1 = new byte[8192];      int count1 = 0;      while ( (count1 = BISServer.read(byte1, 0, byte1.length)) > -1)      {        BOSClient.write(byte1, 0, count1);        BOSClient.flush();      }    }    catch (java.io.FileNotFoundException e)    {      try      {        //如果文件不存在给出文件不存在的信号        BOSClient.write("404".getBytes());        BOSClient.flush();      }      catch (IOException IOE)      {        IOE.printStackTrace();      }    }    catch (Exception exception)    {      exception.printStackTrace();    }    finally    {      try      {        if (BRClient != null)        {          BRClient.close();        }        if (BOSClient != null)        {          BOSClient.close();        }        if (BISServer != null)        {          BISServer.close();        }        if (socket != null)        {          socket.close();        }        if (SSocket != null)        {          SSocket.close();        }      }      catch (Exception exception)      {        exception.printStackTrace();      }    }  }  public static void main(String[] args)  {    DownloadingFileServer DFServer = new DownloadingFileServer();    DFServer.Service();  }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -