- package TCP;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileReader;
- import java.io.InputStream;
- import java.io.PrintWriter;
- import java.net.Socket;
- public class CopyFileClient {
- /**
- * @param args
- * Tcp复制文件:通过网络传输文件
- */
- public static void main(String[] args) throws Exception{
- // TODO Auto-generated method stub
- //创建客户端的socket服务
- Socket s = new Socket("172.33.2.240",10006);
- //传送文件
- FileReader fReader = new FileReader(new File("e:\\CutDemo.java"));
- BufferedReader bReader = new BufferedReader(fReader);
- PrintWriter bout = new PrintWriter(s.getOutputStream(),true);
- String string = null;
- while((string = bReader.readLine())!=null){
- bout.write(string);
- }
- s.shutdownOutput();//关闭客户端的输出流。相当于给流中加入一个结束标记-1.
- //获取服务端信息
- InputStream bin = s.getInputStream();
- byte[] buff = new byte[1024];
- int length = bin.read(buff);
- String server = new String(buff,0,length);
- System.out.println("server info:"+server);
- //关闭资源
- fReader.close();
- s.close();
- }
- }
- package TCP;
- import java.io.BufferedReader;
- import java.io.FileWriter;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.io.PrintWriter;
- import java.net.ServerSocket;
- import java.net.Socket;
- public class CopyFileServer {
- /**
- * @param args
- * Tcp复制文件:通过网络传输文件
- */
- public static void main(String[] args) throws Exception {
- // TODO Auto-generated method stub
- //创建服务端socket服务
- ServerSocket ss = new ServerSocket(10006);
- //获取客户端的 socket 服务
- Socket s = ss.accept();
- //获取客户端的Ip
- String ip = s.getInetAddress().getHostAddress();
- System.out.println(ip+"...connect");
- //获取服务端的文件
- BufferedReader bin = new BufferedReader(new InputStreamReader(s.getInputStream()));
- PrintWriter pw = new PrintWriter(new FileWriter("E:\\test\\client.java",true));//新建一个可写的文件
- String string = null;
- while((string= bin.readLine())!=null){
- pw.println(string);//按行来存储数据
- }
- OutputStream bout = s.getOutputStream();
- byte[] data = "文件传输成功".getBytes();
- bout.write(data, 0, data.length);
- //关闭资源
- pw.close();
- s.close();
- ss.close();
- }
- }
复制代码 代码不能完成文件复制的功能,但是不知道问题出在哪啦(都快看蒙啦),请高手指点。
|