- 使用TCP协议写一个可以上传文件的服务器和客户端。
- * 思路:网络编程与IO流相拼命
- * 客户端通过socket向其输出流中写入本地文件,用到FileInputStream读取文件,也可加上缓冲BufferedInputStream.
- * 还有通过socket的输入流读取服务器端的反馈信息。
- * 服务端通过socket从其输入流中读取文件,存入到服务器端,并返回文件复制情况信息
- * 资源关闭
- * */
- import java.net.*;
- import java.io.*;
- public class FileLoader {
-
- public static void main(String[] args) {
-
- }
-
- }
-
- //客户端
- class client {
- public static void main(String[] args) throws Exception {
- //建立Socket服务
- Socket fileLoaderSocket = new Socket("127.0.0.1", 10005);
- //从客户端本地读取文件,并写入socket的输出流中
- OutputStream out = fileLoaderSocket.getOutputStream();
- InputStream fileRead = new FileInputStream("G:\\Demo.mp3");
-
- byte[] buf = new byte[1024];
- int len = 0;
- while((len=fileRead.read(buf)) != -1) {
- out.write(buf, 0, len);
- }
- //告诉服务端,文件已传输完毕
- fileLoaderSocket.shutdownOutput();
-
- //获取从服务端反馈的信息
- BufferedReader in = new BufferedReader(new InputStreamReader(fileLoaderSocket.getInputStream()));
- String serverBack = in.readLine();
- System.out.println(serverBack);
-
- //资源关闭
- fileLoaderSocket.close();
- fileRead.close();
- }
- }
-
- //服务端
- class Server {
- public static void main(String[] args) throws Exception {
- //建立服务端Socket
- ServerSocket ss = new ServerSocket(10005);
- //接收客户端Socket
- Socket fileLoaderSocket = ss.accept();
-
- //打印连接信息
- String ip = fileLoaderSocket.getInetAddress().getHostAddress();
- System.out.println(ip + "...conncected");
-
- //接收文件,并保存
- InputStream in = fileLoaderSocket.getInputStream();
- OutputStream fileSave = new FileOutputStream("E:\\server.mp3");
- byte[] buf = new byte[1024];
- int len = 0;
- while((len=in.read(buf)) != -1) {
- fileSave.write(buf, 0, len);
- fileSave.flush();
- }
- //返回文件复制情况信息
- BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fileLoaderSocket.getOutputStream()));
- out.write("文件上传成功");
- out.flush();
-
- //资源关闭
- ss.close();
- fileLoaderSocket.close();
- fileSave.close();
- }
- }
复制代码
总感觉哪里错了,请高手指正。
|
|