Introduction to the

Network programming is how to realize the communication between two computers in the program.

TCP implementation chat

TCP requires two ports, the client and the server, for the chat function

Directly to the code, details and code explanations are in the code comments

The client

package demo01;

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

/ / the client
// 1. Connect to the server Socket
// 2. Send information
public class TcpClient {
    public static void main(String[] args) {
        OutputStream os = null;
        Socket socket = null;
        try {
            / / IP service
            InetAddress ip = InetAddress.getByName("127.0.0.1");
            // Service port
            int port = 7788;
            // Connect to the server through IP and port number
            socket = new Socket(ip, port);
            // Send information through the stream
            os = socket.getOutputStream();
            os.write("Hello?".getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // Close the stream and connection services to avoid wasting resources
            if(os ! =null) {
                try {
                    os.close();
                } catch(IOException e) { e.printStackTrace(); }}if(socket ! =null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}

Copy the code

The server

package demo01;

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

/ / the server
// Create a service port
// Wait for the user to connect
// Receive messages sent by the user
/ / close the flow
public class TcpServer {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            // Create a service port
            serverSocket = new ServerSocket(7788);
            // Wait for the connection from the user, accept the connection
            socket = serverSocket.accept();

            // Accept the message sent by the user
            is = socket.getInputStream();
            Print information through ByteArrayOutputStream
            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while((len = is.read(buffer)) ! = -1) {
                baos.write(buffer, 0, len);
            }
            System.out.println(baos.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(baos ! =null) {
                try {
                    baos.close();
                } catch(IOException e) { e.printStackTrace(); }}if(is ! =null) {
                try {
                    is.close();
                } catch(IOException e) { e.printStackTrace(); }}if(socket ! =null) {
                try {
                    socket.close();
                } catch(IOException e) { e.printStackTrace(); }}if(serverSocket ! =null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Copy the code

Test: first open the service on the server, and then open the client for access. The server receives the information sent by the client

TCP implements file uploading

The client

package demo02;

// File upload

/ / the client
/* 1. Obtain the port and IP address of the server. 2. Upload a file. 4. Tell the server that the file is sent. 5. Close the resource */

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

public class TcpClient {
    public static void main(String[] args) {
        Socket socket = null;
        FileInputStream fileInputStream = null;
        OutputStream outputStream = null;
        InputStream inputStream = null;
        ByteArrayOutputStream baos = null;
        try {
            // Get the server port and IP address
            InetAddress ip = InetAddress.getByName("127.0.0.1");
            int port = 7899;
            // Connect to the server
            socket = new Socket(ip, port);
            // Upload the file
            fileInputStream = new FileInputStream(new File("3.jpg"));// Read the file
            outputStream = socket.getOutputStream();/ / the output stream

            byte[] buffer = new byte[1024];
            int len;
            while((len = fileInputStream.read(buffer)) ! = -1) {
                outputStream.write(buffer, 0, len); // Write out the file
            }
            // Tell the server that sending the file is complete
            socket.shutdownOutput();

            // Get the message received by the server
            inputStream = socket.getInputStream();
            baos = new ByteArrayOutputStream();
            byte[] buffer1 = new byte[1024];
            int len1;
            while((len1 = inputStream.read(buffer1)) ! = -1) {
                baos.write(buffer1, 0, len1);
            }
            System.out.println(baos.toString());// Prints information

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // Close the resource
            if(baos! =null) {try {
                    baos.close();
                } catch(IOException e) { e.printStackTrace(); }}if(inputStream ! =null) {
                try {
                    inputStream.close();
                } catch(IOException e) { e.printStackTrace(); }}if(outputStream ! =null) {
                try {
                    outputStream.close();
                } catch(IOException e) { e.printStackTrace(); }}if(fileInputStream ! =null) {
                try {
                    fileInputStream.close();
                } catch(IOException e) { e.printStackTrace(); }}if(socket ! =null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Copy the code

The service side

package demo02;

// File upload

/ / the server

/* 1. Create a service port 2. Wait for the user to connect 3. Notifies the user that the file has been received. 5. Close the resource */

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

public class TcpServer {
    public static void main(String[] args) {
        ServerSocket serverSocket=null;
        Socket socket = null;
        FileOutputStream fileOutputStream=null;
        InputStream inputStream= null;
        OutputStream outputStream=null;
        try {
            // Create a service port
            serverSocket = new ServerSocket(7899);
            // Wait for the user to connect
             socket = serverSocket.accept();
            Kity. JPG is the file you downloaded
            fileOutputStream = new FileOutputStream(new File("kity.jpg"));
            inputStream = socket.getInputStream();/ / input stream

            byte[] buffer = new byte[1024];
            int len;
            while((len=inputStream.read(buffer))! = -1){
                fileOutputStream.write(buffer,0,len);
            }

            // Notifies the user that information about the file has been received
            outputStream = socket.getOutputStream();
            outputStream.write("Uploaded file received".getBytes());

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // Close the resource
            if(outputStream! =null) {try {
                    outputStream.close();
                } catch(IOException e) { e.printStackTrace(); }}if(inputStream! =null) {try {
                    inputStream.close();
                } catch(IOException e) { e.printStackTrace(); }}if(fileOutputStream! =null) {try {
                    fileOutputStream.close();
                } catch(IOException e) { e.printStackTrace(); }}if(socket! =null) {try {
                    socket.close();
                } catch(IOException e) { e.printStackTrace(); }}if(serverSocket! =null) {try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Copy the code

UDP implements sending information

The client

package demo03;

import java.net.*;

// Send a message
/* set up a datagramSocket; /* Set up a datagramSocket; /* Set up a datagramSocket; 4. Close the stream */
public class UdpClient {
    public static void main(String[] args) throws Exception {
        // Create a datagramSocket
        DatagramSocket datagramSocket = new DatagramSocket();

        // The message sent
        String message = "UDP send message";
        InetAddress ip = InetAddress.getByName("127.0.0.1");
        int port = 9999;
        / / set up a package
        DatagramPacket datagramPacket = new DatagramPacket(message.getBytes(),0,message.getBytes().length,ip,port);
        / / send the package
        datagramSocket.send(datagramPacket);

        / / close the flowdatagramSocket.close(); }}Copy the code

The service side

package demo03;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

// Wait for the client to connect
/* 1. Open port 2. Receive packets 3. Print the received message. 5. Close the stream */
public class UdpServer {
    public static void main(String[] args) throws Exception {
        // Open the port
        DatagramSocket datagramSocket = new DatagramSocket(9999);
        // Receive packets
        byte[] buffer = new byte[1024];
        DatagramPacket datagramPacket = new DatagramPacket(buffer,0,buffer.length);
        // block reception
        datagramSocket.receive(datagramPacket);
        // Prints the received message
        System.out.println(datagramPacket.getAddress().getHostAddress());
        System.out.println(new String(datagramPacket.getData(),0,datagramPacket.getLength()));
        / / close the flowdatagramSocket.close(); }}Copy the code

UDP implements circular sending of information

The client

package demo04;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.*;

public class UdpClient {
    public static void main(String[] args) throws Exception {
        DatagramSocket datagramSocket = new DatagramSocket(8888);

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

        // Loop to send information
        while(true){
            String data = bufferedReader.readLine();
            byte[] bytes = data.getBytes();
            InetAddress ip = InetAddress.getByName("127.0.0.1");
            int port = 7777;

            DatagramPacket datagramPacket = new DatagramPacket(bytes,0,bytes.length,ip,port);
            datagramSocket.send(datagramPacket);

            if (data.equals("bye")) {break; } } bufferedReader.close(); datagramSocket.close(); }}Copy the code

The service side

import java.net.DatagramPacket; import java.net.DatagramSocket; public class UdpServer { public static void main(String[] args) throws Exception { DatagramSocket datagramSocket = new DatagramSocket(7777); // Loop to receive information while(true){byte[] bytes = new byte[1024]; DatagramPacket datagramPacket = new DatagramPacket(bytes,0,bytes.length); datagramSocket.receive(datagramPacket); Byte [] data = datagrampacket.getData (); Receive = new String(data, 0, datagrampacket.getLength ()); System.out.println(receive); if (receive.equals("bye")){ break; } } datagramSocket.close(); }}Copy the code

The client sends a message

The server receives the message

UDP realizes the chat function

Sender utility class

package demo05;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;

// The utility class that sends the message
public class ChatSend implements Runnable{
    DatagramSocket datagramSocket = null;
    BufferedReader bufferedReader = null;

    private int formPort;// The sender port
    private String toIP;// Where to send
    private int toPort;// Receiver port

    public ChatSend(int formPort, String toIP, int toPort) {
        this.formPort = formPort;
        this.toIP = toIP;
        this.toPort = toPort;

        try {
            datagramSocket = new DatagramSocket(formPort);
            bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        } catch(Exception e) { e.printStackTrace(); }}@Override
    public void run(a) {

        while(true) {try {
                String data = bufferedReader.readLine();
                byte[] bytes = data.getBytes();

                DatagramPacket datagramPacket = new DatagramPacket(bytes,0,bytes.length,new InetSocketAddress(this.toIP,this.toPort));
                datagramSocket.send(datagramPacket);
                if (data.equals("bye")) {break; }}catch(IOException e) { e.printStackTrace(); }}try {
            bufferedReader.close();
        } catch(IOException e) { e.printStackTrace(); } datagramSocket.close(); }}Copy the code

Receiver utility class

package demo05;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

// The utility class that receives the information
public class ChatReceive implements Runnable{
    DatagramSocket datagramSocket = null;
    private int port; // Open receive port
    private String messageFrom;// Who sent it

    public ChatReceive(int port, String messageFrom) {
        this.port = port;
        this.messageFrom = messageFrom;
        try {
            datagramSocket = new DatagramSocket(this.port);
        } catch(SocketException e) { e.printStackTrace(); }}@Override
    public void run(a) {

        while(true) {byte[] bytes = new byte[1024];
            DatagramPacket datagramPacket = new DatagramPacket(bytes,0,bytes.length);
            try {
                datagramSocket.receive(datagramPacket);
            } catch (IOException e) {
                e.printStackTrace();
            }
            byte[] data = datagramPacket.getData();
            String receive = new String(data, 0, datagramPacket.getLength());
            System.out.println(messageFrom+":"+receive);
            if (receive.equals("bye")) {break; } } datagramSocket.close(); }}Copy the code

Chat With Person A

package demo05;

public class teacher {
    public static void main(String[] args) {
        new Thread(new ChatSend(5555."localhost".3333)).start();
        new Thread(new ChatReceive(2222."Student")).start(); }}Copy the code

Chat Partner B

package demo05;
/* ChatSend: send A message from port A to port B ChatReceive: Open port C the student sends from port 1111 to port 2222, which is open to the teacher, and open port 3333, which is open to the teacher from port 4444, and open port 2222, which is open to the student */
public class student {
    public static void main(String[] args) {
        new Thread(new ChatSend(1111."localhost".2222)).start();
        new Thread(new ChatReceive(3333."Teacher")).start(); }}Copy the code

The URL to download

Download resources, such as music, from their location

package demo06;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class URLDownload {
    public static void main(String[] args) throws Exception {
        // Download the URL of a song
        URL url = new URL("https://m801.music.126.net/20210511221102/9eddb962693b3e07a99d444cf05d8921/jdyyaac/5252/0f09/0e0b/e824f0ca5a8c5dcae8509 aa056e2fa04.m4a");
        // Connect to the address of the resource
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        / / download
        InputStream inputStream = urlConnection.getInputStream();
        FileOutputStream fileOutputStream = new FileOutputStream("music1.m4a");
        byte[] buffer = new byte[1024];
        int len;
        while((len=inputStream.read(buffer))! = -1){
            fileOutputStream.write(buffer,0,len);
        }
        // Close the resourcefileOutputStream.close(); inputStream.close(); urlConnection.disconnect(); }}Copy the code

Then, through the format factory, you can convert the song to MP3 format.