TCP文件上传 发表于 2019-08-15 更新于 2019-08-26 分类于 Java 阅读次数: TCP文件上传实现文件上传与服务器文件下载与拷贝。 文件服务器:1234567891011121314151617181920212223242526272829/** * 文件服务器(下载|拷贝): * 1.指定端口,使用ServerSocket创建服务器 * 2.阻塞式等待链接 accept 返回一个Socket * 3.操作:输入输出流 * 4.释放资源 */public class File_Server { public static void main(String[] args) throws Exception { System.out.println("-------Server-------"); //1.指定端口,使用ServerSocket创建服务器 ServerSocket SS=new ServerSocket(6666); // 2.阻塞式等待链接 accept Socket Client=SS.accept(); System.out.println("客户端连接已建立"); // 3.操作:输入输出流 InputStream buf=new BufferedInputStream(Client.getInputStream()); OutputStream bof=new BufferedOutputStream(new FileOutputStream("c.txt")); byte b[]=new byte[1024]; while(buf.read(b)!=-1) { bof.write(b); } bof.flush(); // 4.释放资源 bof.close(); buf.close(); Client.close(); }} 文件客户端:12345678910111213141516171819202122232425/** * 文件客户端(上传): * 1.建立连接:使用Socket创建客户端:服务器地址和端口 * 2.操作:输入输出流 * 3.释放资源 */public class File_Client { public static void main(String[] args) throws Exception { System.out.println("-------Client-------"); //1.建立连接:使用Socket创建客户端:服务器地址和端口 Socket S=new Socket("localhost",6666); // 3.操作:输入输出流 InputStream buf=new BufferedInputStream(new FileInputStream("D:/javawork/java 17级软工学生体测数据统计系统/用户信息.txt")); OutputStream bof=new BufferedOutputStream(S.getOutputStream()); byte b[]=new byte[1024]; while(buf.read(b)!=-1) { bof.write(b); } bof.flush(); // 4.释放资源 S.close(); buf.close(); bof.close(); }} 原创技术分享,您的支持将鼓励我继续创作 打赏 微信支付 支付宝