Socket下载一个文本文件

来源:互联网 发布:jav网络机顶盒v6 编辑:程序博客网 时间:2024/04/30 22:09
package com.lanqiao.demo2;import java.io.BufferedInputStream;import java.io.FileInputStream;import java.io.IOException;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;/** * @author  * @version 创建时间:2017年6月12日 上午8:47:37  * 类说明:服务端上传一个txt类型的文件 * 注意:服务端是一直不关闭的 */public class TestServer {// 这个路径是我电脑上的一个记事本文件private static final String PATH = "D:\\JavaFile_Test\\test\\网上JDK环境变量配置.txt";public static void main(String[] args) {int count = 0;OutputStream os = null;ServerSocket severscoket = null;Socket s1 = null;BufferedInputStream bis =null;int len=0;try {// 创建 Socket 服务severscoket = new ServerSocket(8888);while (true) {// 阻塞s1 = severscoket.accept();//服务端被连接的次数count++;System.out.println("---服务端开启  " + count + " 次---");// 服务端写入文件os = s1.getOutputStream();//创建一个BufferedInputStream对象读取我电脑上的文件bis = new BufferedInputStream(new FileInputStream(PATH));//每次写入512个字节byte[] b = new byte[512];while ((len = bis.read(b)) != -1) {os.write(b, 0, len);}s1.shutdownOutput();os.flush();}} catch (IOException e) {// TODO 自动生成的 catch 块e.printStackTrace();} finally {try {if (os != null)os.close();} catch (IOException e) {// TODO 自动生成的 catch 块e.printStackTrace();}}}}package com.lanqiao.demo2;import java.io.BufferedInputStream;import java.io.IOException;import java.net.Socket;/** * @author  * @version 创建时间:2017年6月12日 上午9:04:36  * 类说明:客户端打印出从服务端下载的txt内容 */public class TestClient {public static void main(String[] args) {BufferedInputStream bis = null;Socket socket = null;int len=0;try {// 通过IP地址和端口号创建一个Socket对象socket = new Socket("127.0.0.1", 8888);// 客户端读取文件bis = new BufferedInputStream(socket.getInputStream());// 每次读512个字节byte[] b = new byte[512];//当读取的字节不为空  循环打印下载的内容while ((len = bis.read(b)) != -1) {System.out.println(new String(b, 0, len));}} catch (IOException e) {// TODO 自动生成的 catch 块e.printStackTrace();} finally {//关闭客户端的输入流对象 和  Socket对象try {if(bis!=null) bis.close();if(socket!=null) socket.close();} catch (IOException e) {// TODO 自动生成的 catch 块e.printStackTrace();}}}}
 
 

原创粉丝点击