计算机网络——Socket实验3

  • 实验过程

关于TCP协议的Socket和ServerSocket类的相关内容已经在前面实验5-1和实验5-2介绍完毕,此处不作赘述。

1 代码描述

首先,对于服务器端可编写代码如下,如代码 1先引入必要的包:

代码 1 服务端引入必要的包

然后定义如代码 2的文件服务类,包含连接客户端的socket,服务端的server_socket,端口port,文件路径file_path,以及字节流大小buffersize五个成员变量以及用于获取文件列表的getFileList方法,创建连接的getConnect方法和用于执行的run方法。

代码 2 服务端定义文件服务类

对于代码 3中的getFileList方法,先输出提示语,并利用工作目录创建文件获取文件列表,遍历文件列表进行判断,仅输出是文件的目录,如果是路径则不进行输出。并用Scanner获取输入以获得要进行传输的文件的名字。

代码 3 服务端getFileList方法

对于代码 4中的getConnect方法,利用代码 3中的getFileList方法获取的文件名读对应的文件。在接受客户端的Socket后,使用重定向的字符流将文件的名字和文件内容通过socket传给客户端。完成传输后清空缓冲区并关闭socket。

代码 4 服务端getConnect方法

对于代码 5中的run方法,依次执行代码 3中的getFileList方法和代码 4中的getConnect方法即可。

代码 5 服务端的run方法

对于客户端,也要引入如代码 6的库:

代码 6 客户端的库

       定义如代码 7的客户端文件类,包含连接客户端的client_socket,IP,端口port,文件保存路径save_path,以及字节流大小buffersize五个成员变量以及用于创建连接的getConnect方法。

代码 7 客户端定义文件类

对于如的getConnect方法,通过ip和port创建socket后借助buffer流,获取服务端的文件流,并借助重定向将文件保存下来。

代码 8 客户端getConnect方法

2 测试运行

首先,运行服务端。将显示如图 1的文件列表。

1 文件列表

在此以传输test.txt为例,输入test.txt。结果如图 2

2 选择test.txt进行测试

紧接着,客户端开始建立连接,获取文件并自动重命名如图 3

3 客户端建立连接并获取文件

完成传输后,服务端也给出如图 4的提示。

4 服务端完成传输

最后检验一下传输的结果,如图 5,可以看到传输成功。

5 传输结果

【附件】

Client.java

import java.io.*;
import java.net.*;

public class File_client {
    private Socket Client_Socket;                           //Create the client socket
    private String ip = "localhost";                        //Create the string of IP which has the default value set to "localhost"
    private int buffersize = 1024;
    private int port = 6574;
    private String save_path;             //Create the string of save path

    private void getConnect() {
        try {
            Client_Socket = new Socket(ip, port);            //Try to connect to the server socket
            System.out.println("Connection is built.");

            DataInputStream in = new DataInputStream(Client_Socket.getInputStream());
            String get_path = in.readUTF();
            save_path = "./received_" + get_path;
            DataOutputStream out = new DataOutputStream(Client_Socket.getOutputStream());
            DataOutputStream file_out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(save_path)));
            //Try to read the content from the server
            System.out.println("Receiving " + get_path);
            System.out.println("Saving in " + save_path);
            byte[] buffer = new byte[buffersize];           //Use buffer to store the data
            int length = 0;
            while ((length = in.read(buffer, 0, buffer.length)) > 0) {
                file_out.write(buffer, 0, length);          //Write out the data
                file_out.flush();
            }
            System.out.println("Finished " + save_path);
            file_out.close();
        } catch (Exception e) {
            System.out.println("Error:" + e);
        }
    }

    public static void main(String[] args) {
        new File_client().getConnect();
    }
}

Server.java

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class File_server {
    private Socket socket;                               //Create the socket to connect to the client
    private ServerSocket server_socket;                  //Create the server socket
    private int port = 6574;
    private String file_path;                            //the path of the file
    private int buffersize = 1024;

    void getFileList() throws IOException {
        System.out.println("Choose your file to transfer!");
        System.out.println("====================================");
        File file = new File(new File("").getCanonicalPath());
        File[] files = file.listFiles();
        for (File f : files) {
            if (f.isFile()) {
                System.out.println(f.getName());
            }
        }
        Scanner scanner = new Scanner(System.in);
        file_path = scanner.next();
    }

    void getConnect() {
        try {
            server_socket = new ServerSocket(port);         //Set server socket using the same port
            File file = new File(file_path);
            System.out.println("============Server is on============");
            socket = server_socket.accept();             //Try to connect to the client
            System.out.println("============Connection is built============");
            DataInputStream in = new DataInputStream(socket.getInputStream());
            DataInputStream file_in = new DataInputStream(new BufferedInputStream(new FileInputStream(file_path)));
            DataOutputStream out = new DataOutputStream(socket.getOutputStream());
            System.out.println("Sending file: " + file_path);
            out.writeUTF(file.getPath());                //Write in the file path to the client
            out.flush();
            byte[] buffer = new byte[buffersize];
            int length = 0;
            while ((length = file_in.read(buffer, 0, buffer.length)) > 0) {
                out.write(buffer, 0, length);            //Write in the file content to the client
                out.flush();
            }
            System.out.println("Finished.");
            out.flush();
            file_in.close();
            socket.close();
            server_socket.close();
        } catch (IOException e) {
            System.out.println("Error!");
            System.out.println(e);
        }
    }

    void run() throws IOException {
        getFileList();
        getConnect();
    }

    public static void main(String[] args) throws IOException {
        new File_server().run();
    }
}

猜你喜欢

转载自blog.csdn.net/m0_46326495/article/details/124375181