Java foundation of network communication protocol and UDP --TCP

Personal understanding:

  Learn to distinguish between different UDP and TCP, the normal usage patterns are a combination of both! For better transport, often open multiple threads for transmission!

A network communication protocol:

1, TCP / IP protocol:

Four layers: the application layer, transport layer, network layer and link layer:

Link layer: the link layer is used to define the physical transmission channel, is usually connected to a drive device for certain protocol network, for example, optical drives, cable provided.

Network layer: The network layer is the core of the TCP / IP protocol, which is mainly used for the transmitted data packet, transmits the packet data to the destination computer or network.

Transport Layer: The main program that the communication network during network communication, may employ TCP protocol, the UDP protocol may be used.

Application layer: mainly responsible for the application of the protocol, such as HTTP protocol, FTP protocol.

2, IP address and port number:

①, IP address, which uniquely identifies a computer:

  Formerly IPV4, IPV6 is now 16 bytes of address.

②, port number: two bytes: 0-65535. Generally more than 1024 port number.

3, InetAddress class:

 

{class Demo01 public
    public static void main (String [] args) {throws UnknownHostException
        InetAddress inet = InetAddress.getByName ( "192.168.1.163"); // ip address which is own
        // IP address acquired from the subject
        System.out .println (inet.getHostAddress ());
        // get the host name
        System.out.println (inet.getHostName ());
        // get local host ip objects
        InetAddress inet2 = InetAddress.getLocalHost ();
        System.out.println ( inet2.getHostAddress ());
        System.out.println (inet2.getHostName ());
    }
}

 

 Two, UDP and TCP protocol:

1, UDP protocol:

  User Datagram Protocol User Datagram Protocol - connectionless protocol: You can not guarantee data integrity, revel! ! ! 64K or less.

2, TCP protocol:

  Transmission Control Protocol --- transmission control protocol connection-oriented communication protocol:

Establishing a logical connection to the transmitting and receiving ends of data prior to transmission, before data is transmitted.

  TCP connection must be clear client and server, a connection request to the server from the client, create each connection needs to go through "three-way handshake." The first handshake, the client sends a connection request to the server, waiting for the server to confirm, second handshake, the server to send a response back to the client, the client receives a notification connection request, third handshake, the client to the server again sends a confirmation message to confirm the connection.

Three, UDP communications:

1, DatagramPacket: data package the class:

UDP encapsulation data for transmitting or receiving communication.

2, DatagramSocket: "Terminal": can send and receive data packets DatagramPacket

 

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

// transmitting end
public class UDPSend {
    public static void main (String [] args) throws IOException {
        // encapsulated data
        byte [] bytes = "Hello the UDP" .getBytes ();
        // ip address encapsulation
        InetAddress inet = InetAddress. the getByName ( "127.0.0.1");
        // 1. Create data packing object encapsulating data to be transmitted, the length, the receiving end of the IP address and port number
        of DatagramPacket of DatagramPacket new new DP = (bytes, bytes.length, inet, 6000);
        . 2 // Create DatagreamSocket objects (Express)
        DatagramSocket DS DatagramSocket new new = ();
        // send packets. 3.
        ds.send (DP);
        // release resources
        ds.close ();
    }
}

 

 

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

// receiving end
public class UDPReceive {
    public static void main (String [] args) throws IOException {
        // create DatagramSocket object, a clear port number
        DatagramSocket new new DS = DatagramSocket (6000);
        . 2 // Create responsible for handling incoming byte array data to
        byte [] bytes = new new byte [1024];
        .. 3 // Create a data unpacking objects
        of DatagramPacket of DatagramPacket new new DP = (bytes, bytes.length);
        //. 4 receives the packet.
        ds.receive (DP);
        // unpacking 5
        // get the received data length
        int length = dp.getLength ();
        // get the IP address of the sender
        String dp.getAddress IP = () getHostAddress ();.
        // get the port number of the transmitting side
        int port = dp.getPort ();
        System.out.println ( "ip address is:" + ip + "port number:" + port + "content transmission is:" + new new String (bytes, 0, length));
    }
}

 

 Four, TCP communication:

1, ServerSocket categories: the server side; the Socket class: the client.

 

 

 

// client
public class TCPClient {
    public static void main (String [] args) throws UnknownHostException, IOException {
        // 1. Create a Socket object, the server address and port number to connect to clear
        Socket socket = new Socket ( "127.0.0.1 ", 8888);
        // 2 clear data source.
        the FileInputStream new new FIS = the FileInputStream (" D: \\ \\ a.txt Java ");
        .. 3 // Get the byte stream output from the object socke, ready to read server file bytes written
        the OutputStream Socket.getOutputStream OUT = ();
        .. 4 starts copying //
        int len = 0;
        byte [] bytes = new new byte [1024];
        the while ((len = fis.read (bytes))! -1 =) {
            out.write (bytes, 0, len);
        }
        // end of the output stream, the server tells the end, do not read
        socket.shutdownOutput ();
        return // receiving server
        // Get an object from the socket input stream of bytes, the data server replies received
        the InputStream in Socket.getInputStream = ();
        len = in.read (bytes);
        System.out.println (new new String (bytes, 0, len));
        // release resources
        the Socket.close ();
        fis.close ();
    }
}

 

2, multi-threaded transfer:

 

// thread task object
public class the Upload the implements Runnable {
    Private the Socket socket;

    public Upload() {
    };

    public Upload(Socket socket) {
        this.socket = socket;
    };

    RUN void public () {
        FileOutputStream fos = null;
        the try {
            // clear destination 3.
            File File = new new File ( "D: \\ NiHao");
            // If the directory does not exist, create
            if (file.exists! ()) {
                file.mkdirs ();
            }
            String filename = "Oracle" + System.currentTimeMillis () + ".txt";
            // clear destination
            fos = new new a FileOutputStream (File the File.separator + + filename);
            // clear data source
            the InputStream in Socket.getInputStream = ();
            // start copying
            int len = 0;
            byte [] bytes = new new byte [1024];
            the while (! (len = in.read (bytes)) = -1) {
                fos.write (bytes, 0, len);
            }
            // replies to the client
            // Get an output stream of bytes, replies to the client
            the OutputStream Socket.getOutputStream OUT = ();
            out.write ( "successful upload" .getBytes ()) ;
        } the catch (IOException EX) {
            ex.printStackTrace ();
        } the finally {
            // release resources
            the try {
                fos.close ();
            } the catch (IOException E) {
                // the TODO Auto-Generated Block the catch
                e.printStackTrace ();
            }
        }

    }
}

 

 

public class Demo {

    static void main public (String [] args) throws IOException {
        .. 1 // server object is created
        the ServerSocket Server new new = the ServerSocket (8888);
        the while (to true) {
            // create a connection client object acquired
            Socket socket = server.accept () ;
            / * // create a thread (the thread creation task)
            new new the thread (new new the Upload (socket)) Start ();. * /
            // create a thread task
            the Upload new new up = the Upload (socket);
            // create a thread object
            thread thread = the thread new new (up);
            // open thread
            Thread.start ();
           
        }

    }

}

 

Guess you like

Origin www.linuxidc.com/Linux/2019-07/159674.htm