Day23-3.TCP programming

1 TCP programming

  1. TCP programming steps
    client:
    1. Create a Socket object and establish a connection with the server
    2. Obtain network output stream
    3. Send data through I\O operation
    4. Close resources
    Server:
    1. Create a ServerSocket object, start the server and listen to the specified port
    2. Call the accept method to receive the request from the client and return a Socket object
    3. Obtain the network input stream of the server
    4. Read data through I\O operation
    5. Close resources
  2. Client connection method:
    Socket(InetAddress ip, int port): a communication point is established to communicate with the port program of the ip host.
    getOutputStream(): get the output stream object of the client, which is used to write out information
    be careful:
    After the object is created and started successfully, it indicates that a connection has been established with the server, otherwise the connection fails
  3. Connection method of the server:
    ServerSocket(int port): create a server port object to connect to the client
    accept(): get a Socket object that interacts with the client
    getInputStream(): get the input stream, which is used to receive data from the client

1.1 client code

package tcp.demo1;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
    public static void main(String[] args) throws IOException {

        //1. Create a communication point to connect with the server
        Socket sk = new Socket(InetAddress.getByName("192.168.38.226"),10010);
        //2. To get a network stream to send information
        OutputStream os = sk.getOutputStream();
        //3. Using the send function in the stream
        String str = "Hello";
        os.write(str.getBytes());
        //4. Just close it
        sk.close();
    }
}

1.2 server

package tcp.demo1;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws IOException {
        //1. You need to establish a port to connect with the client first
        ServerSocket ssk = new ServerSocket(10010);
        //2. Gets a port used to receive client information
        Socket sk = ssk.accept();
        //3. Get an input stream and read information
        InputStream is = sk.getInputStream();
        byte[] bs = new byte[1024];
        int len = is.read(bs);
        System.out.println(new String(bs,0,len));
        //4. Close communication point
        ssk.close();
    }
}

2 case 1

Requirements:
(1) The client directly sends a string using keyboard input
(2) The server uses efficient stream to read string

2.1 client code

package tcp.demo2;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) throws IOException {
        //Create a communication point for the client
        Scanner sc = new Scanner(System.in);
        Socket sk = new Socket(InetAddress.getByName("192.168.38.226"),10010);
        //Get an output stream
        OutputStream os = sk.getOutputStream();
        //Wrap a byte stream as a character stream:
        OutputStreamWriter osw = new OutputStreamWriter(os);
        //Then wrap the character stream into an efficient character stream:
        BufferedWriter bw = new BufferedWriter(osw);
        //Directly transfer a string:
        while(true){
            System.out.println("Please enter the request you want to send:");
            String str = sc.nextLine();
            if(str.equals("end")){
                break;
            }
            bw.write(str);
            bw.newLine();
            bw.flush();
        }

        //Close communication point
        sk.close();
    }
}

2.2 server code

package tcp.demo2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws IOException {

        //Create a communication point to connect to
        ServerSocket ssk = new ServerSocket(10010);
        //Get a communication point to read data
        Socket sk = ssk.accept();
        //Get an input stream
        InputStream is = sk.getInputStream();
        //Wrap the byte input stream into a character stream
        InputStreamReader isr = new InputStreamReader(is);
        //Then the character stream is wrapped into an efficient character stream
        BufferedReader br = new BufferedReader(isr);
        String str;
        while((str = br.readLine()) != null){
            System.out.println("The data received is:" + str);
        }
        ssk.close();
    }
}

3 case 2

Requirements:
(1) After receiving the request from the client, the server will feed back information to the client
(2) Client receives feedback

3.1 client

package tcp.demo2;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) throws IOException {
        //Create a communication point for the client
        Scanner sc = new Scanner(System.in);
        Socket sk = new Socket(InetAddress.getByName("192.168.38.226"),10010);
        //Get an output stream
        OutputStream os = sk.getOutputStream();
        //Wrap a byte stream as a character stream:
        OutputStreamWriter osw = new OutputStreamWriter(os);
        //Then wrap the character stream into an efficient character stream:
        BufferedWriter bw = new BufferedWriter(osw);
        //Directly transfer a string:
        while(true){
            System.out.println("Please enter the request you want to send:");
            String str = sc.nextLine();
            if(str.equals("end")){
                break;
            }
            bw.write(str);
            bw.newLine();
            bw.flush();

            //Receive feedback from the server:
            InputStream is = sk.getInputStream();
            byte[] bs = new byte[1024];
            int len = is.read(bs);
            System.out.println(new String(bs,0,len));
        }

        //Close communication point
        sk.close();
    }
}

3.2 server

package tcp.demo2;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws IOException {

        //Create a communication point to connect to
        ServerSocket ssk = new ServerSocket(10010);
        //Get a communication point to read data
        Socket sk = ssk.accept();
        //Get an input stream
        InputStream is = sk.getInputStream();
        //Wrap the byte input stream into a character stream
        InputStreamReader isr = new InputStreamReader(is);
        //Then the character stream is wrapped into an efficient character stream
        BufferedReader br = new BufferedReader(isr);
        String str;
        while((str = br.readLine()) != null){
            System.out.println("The data received is:" + str);

            //Give the client a feedback:
            OutputStream os = sk.getOutputStream();
            os.write("Sent successfully".getBytes());
        }
        ssk.close();
    }
//    After receiving the request from the client, the server will feed back information to the client
//    Client receives feedback
}

4 case 3

Requirements: file upload
(1) The client reads data from the file and sends the read data
(2) The server saves the data sent by the client in another specified file

5 case 4

Requirements:
After the file is uploaded successfully, the server will give the message of successful upload to let the client know that the file has been sent successfully

5.1 client code

package tcp.demo3;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
    public static void main(String[] args) throws IOException {

        Socket sk = new Socket(InetAddress.getByName("192.168.38.226"),10010);
        OutputStream os = sk.getOutputStream();
        //Send the information in the file:
        //1. To send a file information, you need to read the information of the file first
        FileInputStream fis = new FileInputStream("day23/zms.jpeg");
        int i;
        while((i = fis.read()) != -1){
            os.write(i);
        }
        fis.close();

        //When the client sends the message, it should give the server an end flag
        sk.shutdownOutput();

        //Receive feedback here
        InputStream is = sk.getInputStream();
        byte[] bs = new byte[1024];
        int len = is.read(bs);
        System.out.println(new String(bs,0,len));
        sk.close();

    }
}

5.2 server code

package tcp.demo3;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket ssk = new ServerSocket(10010);
        Socket sk = ssk.accept();
        InputStream is = sk.getInputStream();

        //To save the read information in another file, you need to create a file output stream
        FileOutputStream fos = new FileOutputStream("day23/zmscopy.jpeg");
        int i;
        while((i = is.read()) != -1){
            fos.write(i);
        }

        //The server sends a feedback message to the client
        OutputStream os = sk.getOutputStream();
        os.write("File upload succeeded!!!".getBytes());

        ssk.close();
        fos.close();
    }
}

6 case 5

Requirements:
The server uses multithreading to receive files sent by multiple users at the same time
Client code unchanged

6.1 server code

package tcp.demo4;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws IOException {
        //The server uses multithreading to save files
        //If multiple clients send files at the same time, the server can allocate multiple threads to store them separately
        ServerSocket ssk = new ServerSocket(10010);
        //Define an endless loop to continuously receive requests from clients
        while(true){
            Socket sk = ssk.accept();
            Task task = new Task(sk);
            //The client sends a request, defines a task, and uses threads to complete the task
            Thread t = new Thread(task);
            t.start();
        }
    }
}

6.2 save information task code

package tcp.demo4;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

//The type can be defined as the save file task
public class Task implements Runnable{

    Socket s = null;
    public Task(Socket s){
        this.s = s;
    }
    static int x = 0;
    @Override
    public void run() {
        x++;
        try {
            InputStream is = s.getInputStream();
            FileOutputStream fos = new FileOutputStream("day23/zmscopy" + x + ".jpeg");
            int i;
            while((i = is.read()) != -1){
                fos.write(i);
            }
            fos.close();

            OutputStream os = s.getOutputStream();
            os.write("File uploaded successfully".getBytes());

            s.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Note: the client code of case 6 is consistent with that of case 5

Keywords: Java TCP/IP

Added by SargeZT on Thu, 16 Dec 2021 01:16:54 +0200