sa- /*
- 上传文本,通过TCP协议
- */
- import java.io.*;
- import java.net.*;
- class Client3
- {
- public static void main(String[] args) throws Exception
- {
- Socket s = new Socket("192.168.31.1",10005);
- File file = new File("TcpDemo.java");
- if(!file.exists())
- throw new RuntimeException();
- String fileName = file.getName();//获取文件名传给主机
- BufferedReader bufr = new BufferedReader(new FileReader(file));
-
- PrintWriter out = new PrintWriter(s.getOutputStream(),true);
- System.out.println("发送文件名...");
-
- out.println(fileName);//串文件名
- //穿文档
- String line = null;
- while((line=bufr.readLine())!=null)
- {
- System.out.println("开始传输...");
- out.println(line);
- }
- System.out.println("发送完毕!!");
- //发送完毕
- s.shutdownOutput();
- //接收主机的回传信息
- BufferedReader buf = new BufferedReader(new InputStreamReader(s.getInputStream()));
-
- System.out.println(buf.readLine());
-
- //关闭资源呢
- buf.close();
- bufr.close();
- out.close();
- s.close();
- }
- }
- class Server3
- {
- public static void main(String[] as) throws Exception
- {
- ServerSocket ss = new ServerSocket(10005);
- Socket s = ss.accept();
- //接收文件名
- BufferedReader bufr = new BufferedReader(new InputStreamReader(s.getInputStream()));
-
-
- String fileName = bufr.readLine();
- System.out.println("接收到文件名!!");
- // File file = new File(fileName+".cpy");
- //复制内容
- BufferedWriter bufw = new BufferedWriter(new FileWriter("copy_"+fileName));
-
- String line = null;
- System.out.println("接收内容...");
- while((line=bufr.readLine())!=null)
- {
- bufw.write(line);
- bufw.newLine();
- bufw.flush();
- }
- //返回成功消息
- PrintWriter out = new PrintWriter(s.getOutputStream(),true);
- System.out.println("接收完毕...");
- out.println("上传成功");
- out.close();
-
- s.close();
- ss.close();
- }
-
- }
复制代码
|
|