Image Upload Based on TCP Protocol

JavaJavaBeginner
Practice Now

Introduction

In this project, you will learn how to build a simple image upload application using the TCP protocol. The application consists of a client and a server, where the client can upload an image to the server, and the server will receive and store the image.

👀 Preview

Unfinished
Unfinished
Unfinished

ðŸŽŊ Tasks

In this project, you will learn:

  • How to set up a server to listen for incoming client connections and receive uploaded images
  • How to implement a client to read a local image file and send it to the server
  • How to handle the communication between the client and the server using TCP sockets
  • How to provide feedback to the client upon successful image upload

🏆 Achievements

After completing this project, you will be able to:

  • Create a server-client architecture using Java
  • Use TCP sockets for file transfer between a client and a server
  • Handle file I/O operations in Java
  • Implement basic error handling and feedback mechanisms

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ConcurrentandNetworkProgrammingGroup(["`Concurrent and Network Programming`"]) java(("`Java`")) -.-> java/FileandIOManagementGroup(["`File and I/O Management`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java/ConcurrentandNetworkProgrammingGroup -.-> java/net("`Net`") java/FileandIOManagementGroup -.-> java/files("`Files`") java/FileandIOManagementGroup -.-> java/io("`IO`") java/BasicSyntaxGroup -.-> java/output("`Output`") subgraph Lab Skills java/net -.-> lab-300368{{"`Image Upload Based on TCP Protocol`"}} java/files -.-> lab-300368{{"`Image Upload Based on TCP Protocol`"}} java/io -.-> lab-300368{{"`Image Upload Based on TCP Protocol`"}} java/output -.-> lab-300368{{"`Image Upload Based on TCP Protocol`"}} end

Set up the Server

In this step, you will learn how to set up the server to receive the uploaded image.

  1. Open the org/labex/service/UploadService.java file in your code editor.

  2. In the main() method, create a ServerSocket object to listen for incoming client connections on port 10203:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
        try (ServerSocket server = new ServerSocket(10203)) {
            // Continuously accept client connections
            while (true) {
                // Server waits
                // Returns the client's Socket if there's a connection
                Socket client = server.accept();
                InetAddress clientAddress = client.getInetAddress();
                // Receive the uploaded image from the client
                // Input stream: Reads the image file stream sent by the client
                // Output stream: Writes to the local image
                String name = "/home/labex/project/pic/mn.jpg";

                try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(name));
                     InputStream in = client.getInputStream();
                     BufferedInputStream bis = new BufferedInputStream(in);) {

                    // Read the image file stream from the client
                    // Write to the local file
                    byte[] buffer = new byte[1024];
                    int length = -1;
                    while ((length = bis.read(buffer)) != -1) {
                        bos.write(buffer, 0, length);
                    }

                    // Output message to the client
                    try (BufferedWriter writer = new BufferedWriter(
                            new OutputStreamWriter(client.getOutputStream()))) {
                        writer.write("Reception Complete");
                        writer.newLine();
                    }
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
  1. The server will continuously accept client connections and receive the uploaded image. The received image will be stored in the /home/labex/project/pic/mn.jpg file.

  2. After receiving the image, the server will send a "Reception Complete" message to the client.

Implement the Client

In this step, you will learn how to implement the client to upload an image to the server.

  1. Open the org/labex/client/UploadClient.java file in your code editor.

  2. In the main() method, create a Socket object to connect to the server at 127.0.0.1:10203:

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
        try (
            // Socket: Component for client communication
            // Reading local image => Sending to server via output stream
            // OutputStream: Sends the local image file stream to the server
            // BufferedInputStream: Reads the local image
            Socket client = new Socket("127.0.0.1", 10203);
            OutputStream out = client.getOutputStream();
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(
                    "/home/labex/project/timg.jpg"))
        ) {
            // Reading 1024 bytes each time
            byte[] buffer = new byte[1024];
            int length = -1;
            while ((length = in.read(buffer)) != -1) {
                // Sending the read content to the server via the output stream
                out.write(buffer, 0, length);
            }
            // Temporary end of "output" (Socket not closed)
            client.shutdownOutput();

            // Reading feedback from the server
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()))) {
                String reply = reader.readLine();
                System.out.println(reply);
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
  1. The client will read the local image file /home/labex/project/timg.jpg and send it to the server using the output stream of the socket.

  2. After sending the image, the client will read the feedback message from the server and print it to the console.

  3. If the server sends the "Reception Complete" message, it means the image upload is successful.

Now, you have completed the implementation of both the server and the client. You can compile and run the programs to test the image upload functionality.

Run

Open a terminal and run the following command to compile your client and server program:

javac org/labex/client/UploadClient.java
javac org/labex/service/UploadService.java

Start the server to listen to the client:

java org.labex.service.UploadService

Open another terminal to start the client to upload image, and you will get the prompt: "Reception Complete"

Unfinished
java org.labex.client.UploadClient

Check if the pic folder contains the image or not:

ls pic

The running effect is as follows:

Unfinished
âœĻ Check Solution and Practice

Summary

Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.

Other Java Tutorials you may like