Java network programming code, development tools, database, server setup and web design

From the big point of view, network programming refers to the sending and receiving of information, and the intermediate transmission is the function of physical lines.

The main job of network programming is to assemble the package of information through a prescribed protocol at the sending end, and parse the package according to the prescribed protocol at the receiving end, so as to extract the corresponding information to achieve the purpose of communication. The most important thing in the middle is the assembly of data packets, the filtering of data packets, the capturing of data packets, the analysis of data packets, and of course, some processing will be done at the end. You need to do the code, development tools, database, server setup and web design. contact.

references

InternetAccess Use of classes

I. Overview

computer network:

  • The computers distributed in different geographical areas and specialized external equipment are interconnected by communication lines to form a large-scale and powerful network system, so that numerous computers can easily transfer information to each other and share resources such as hardware, software, data and information.

The purpose of network programming: directly or indirectly realize data exchange and communication with other computers through network protocols

Two problems need to be solved to realize network communication:

  • How to accurately locate one or more hosts on the network; locate specific applications on the host
  • How to transfer data reliably and efficiently after finding the host

Second, the elements of network communication

  • Solve problem one: IP and port number
  • Solve the second problem: Provide network communication protocol: TCP/IP reference model (application layer, transport layer, network layer, physical + data link layer)

Network communication protocol

Communication process

3. Communication element one: IP and port number

3.1 Understanding of IP

IP: uniquely identifies the computer (communication entity) on the Internet

Use the InetAddress class to represent IP in Java

IP classification: IPv4 and IPv6; World Wide Web and Local Area Network

Domain name: resolve the domain name to an IP address through a domain name resolution server, such as: www.baidu.com www.mi.com www.jd.com

Domain name resolution: The domain name is easy to remember. When the domain name of a host is entered when connecting to the network, the domain name server (DNS) is responsible for converting the domain name into an IP address, so as to establish a connection with the host.

Local loop address: 127.0.0.1corresponding to:localhost

3.2 Port number:

Used to identify the process that is running on the computer.

  • Requirements: different port numbers for different processes
  • Range: It is specified as a 16-bit integer 0~65535.
  • classification:
  • Recognized port: 0~1023. It is occupied by predefined service communication (for example: HTTP occupies port 80, FTP occupies port 21, and TeInet occupies port 23).
  • Registered port: 1024~49151. Assigned to user process or application. (For example: Tomcat occupies port 8080, MSQL occupies port 3306, Oracle occupies port 1521, etc.).
  • Dynamic private port: 49152~65535.

3.3 InetAddress class

An object of this type represents a specific IP address

3.2.1 Instantiation

getByName(String host) /getLocalHost()

3.2.2 Common methods

getHostName() / getHostAddress()

public class InetAddressTest {
    public static void main(String[] args) {
        try {
            //File file = new File("hello.txt");
            InetAddress inet1 = InetAddress.getByName("192.168.10.14");

            System.out.println(inet1);

            InetAddress inet2 = InetAddress.getByName("www.baidu.com");
            System.out.println(inet2);

            InetAddress inet3 = InetAddress.getByName("127.0.0.1");
            System.out.println(inet3);

            //获取本地ip
            InetAddress inet4 = InetAddress.getLocalHost();
            System.out.println(inet4);

            //getHostName()
            System.out.println(inet2.getHostName());
            //getHostAddress()
            System.out.println(inet2.getHostAddress());

        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

4. Communication element two: network communication protocol

4.1 Hierarchical Model

4.2 The difference between TCP and UDP

TCP protocol :

Before using the TCP protocol, a TCP connection must be established to form a data transmission channel

Before transmission, the "three-way handshake" method is adopted for point-to-point communication, which is reliable

Two application processes of TCP protocol for communication: client and server.

Large amount of data can be transferred in the connection

After the transmission is completed, the established connection needs to be released, which is inefficient

UDP protocol:

Encapsulate data, source, and destination into data packets without establishing a connection

The size of each datagram is limited to 64K

Sending is unreliable regardless of whether the other party is ready or not, and the receiving party does not confirm it when it is received.

Can be broadcast

No need to release resources when sending data, low overhead and fast speed

4.3 TCP three-way handshake and four waved hands

5. Socket

The combination of port number and IP address results in a network socket:Socket

The use of sockets ( Socket) to develop network applications has long been widely adopted, so that it has become a de facto standard.

Only the uniquely identified IP address and port number on the network can be combined to form a uniquely identifiable identifier socket.

There must be both ends of the communication Socket, which is the end point of the communication between the two machines.

In fact, network traffic is Socketcommunication between.

SocketAllow the network connection as a program stream, two data Socketpassed between IOtransmission.

Generally, the application that initiates the communication is the client, and the one waiting for the communication request is the server.

Socket classification

  • Stream socket ( stream socket): Use TCP to provide reliable byte stream services
  • Datagram socket ( datagram socket): Use UDP to provide "best effort" datagram service

Three, TCP network programming

Socket programming based on the Java language is divided into client and server

Socket communication model based on TCP

1. TCP programming based on Socke

1.1 Working Process of Client Socket

Created Socket: based on IP address or port number of the server configuration specified Sσcketclass object. If the server responds, a communication line from the client to the server is established. If the connection fails, an exception will occur.

Open a connection to Socketinput a stream: use getInputstream()method to obtain the input stream, using the getOutputStream()method for obtaining the output stream, data transmission

According to a certain protocol for Socketread / write operations: read the server by placing the information in the input stream line (but not read information into its own line), information is written by the thread output stream

Close Socket: Disconnect the connection from the client to the server and release the line

Description :

The client program can use the Socketclass to create an object, created at the same time automatically initiates a connection to the server side.

Socket The constructor is:

  • Socket(String host,int port) throws UnknownHostException, : EXCeptionThe server (the domain name host, port number port) to initiate TCPthe connection, if successful, create Socketobjects, otherwise an exception is thrown.
  • Socket(InetAddress address,int port)throws IOException: The InetAddressobject represents the IPaddress and port number portto initiate a connection

The process of establishing a socketAtClient object by the client is to send a socket connection request to the server

1.2 The working process of the server-side Socket:

Call ServerSocket(int port): Create a server-side socket and bind it to the specified port. Used to monitor client requests.

Call accept0(): listen for connection requests, if the client requests a connection, then accept the connection and return the communication socket object.

Call the Socketclass object getOutputStream()and getInputStream(): acquiring the input stream and output stream, start to send and receive network data.

Close ServerSocketand Socketobjects: the client end of the visit, close communication socket.

Description:

ServerSocketThe object is responsible for waiting for the client's request to establish a socket connection, similar to a salesperson in a window of a post office. In other words, the server must first establish a waiting client requests to establish socket connections Server Socketobjects.

The so-called "reception" client socket requests that accept()the method returns an SocketObject

1.3 Code example

Example 1: The client sends information to the server, and the server displays the data on the console

public class TCPTest1 {

    //客户端
    @Test
    public void client()  {
        Socket socket = null;
        OutputStream os = null;
        try {
            //1.创建Socket对象,指明服务器端的ip和端口号
            InetAddress inet = InetAddress.getByName("192.168.14.100");
            socket = new Socket(inet,8899);
            //2.获取一个输出流,用于输出数据
            os = socket.getOutputStream();
            //3.写出数据的操作
            os.write("你好,我是客户端mm".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.资源的关闭
            if(os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    //服务端
    @Test
    public void server()  {

        ServerSocket ss = null;
        Socket socket = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            //1.创建服务器端的ServerSocket,指明自己的端口号
            ss = new ServerSocket(8899);
            //2.调用accept()表示接收来自于客户端的socket
            socket = ss.accept();
            //3.获取输入流
            is = socket.getInputStream();

            //不建议这样写,可能会有乱码
            //        byte[] buffer = new byte[1024];
            //        int len;
            //        while((len = is.read(buffer)) != -1){
            //            String str = new String(buffer,0,len);
            //            System.out.print(str);
            //        }
            //4.读取输入流中的数据
            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[5];
            int len;
            while((len = is.read(buffer)) != -1){
                baos.write(buffer,0,len);
            }

            System.out.println(baos.toString());

            System.out.println("收到了来自于:" + socket.getInetAddress().getHostAddress() + "的数据");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(baos != null){
                //5.关闭资源
                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(ss != null){
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
   }
}

Example 2: The client sends a file to the server, and the server saves the file locally.

public class TCPTest2 {

    /*
    这里涉及到的异常,应该使用try-catch-finally处理
     */
    @Test
    public void client() throws IOException {
        //1.
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9090);
        //2.
        OutputStream os = socket.getOutputStream();
        //3.
        FileInputStream fis = new FileInputStream(new File("beauty.jpg"));
        //4.
        byte[] buffer = new byte[1024];
        int len;
        while((len = fis.read(buffer)) != -1){
            os.write(buffer,0,len);
        }
        //5.
        fis.close();
        os.close();
        socket.close();
    }

    /*
    这里涉及到的异常,应该使用try-catch-finally处理
     */
    @Test
    public void server() throws IOException {
        //1.
        ServerSocket ss = new ServerSocket(9090);
        //2.
        Socket socket = ss.accept();
        //3.
        InputStream is = socket.getInputStream();
        //4.
        FileOutputStream fos = new FileOutputStream(new File("beauty1.jpg"));
        //5.
        byte[] buffer = new byte[1024];
        int len;
        while((len = is.read(buffer)) != -1){
            fos.write(buffer,0,len);
        }
        //6.
        fos.close();
        is.close();
        socket.close();
        ss.close();

    }
}

Example 3: Send a file from the client to the server, and the server saves it locally. And return "send successfully" to the client.

public class TCPTest3 {

    /*
        这里涉及到的异常,应该使用try-catch-finally处理
         */
    @Test
    public void client() throws IOException {
        //1.
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9090);
        //2.
        OutputStream os = socket.getOutputStream();
        //3.
        FileInputStream fis = new FileInputStream(new File("beauty.jpg"));
        //4.
        byte[] buffer = new byte[1024];
        int len;
        while((len = fis.read(buffer)) != -1){
            os.write(buffer,0,len);
        }
        //关闭数据的输出
        socket.shutdownOutput();

        //5.接收来自于服务器端的数据,并显示到控制台上
        InputStream is = socket.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] bufferr = new byte[20];
        int len1;
        while((len1 = is.read(buffer)) != -1){
            baos.write(buffer,0,len1);
        }

        System.out.println(baos.toString());

        //6.
        fis.close();
        os.close();
        socket.close();
        baos.close();
    }

    /*
    这里涉及到的异常,应该使用try-catch-finally处理
     */
    @Test
    public void server() throws IOException {
        //1.
        ServerSocket ss = new ServerSocket(9090);
        //2.
        Socket socket = ss.accept();
        //3.
        InputStream is = socket.getInputStream();
        //4.
        FileOutputStream fos = new FileOutputStream(new File("beauty2.jpg"));
        //5.
        byte[] buffer = new byte[1024];
        int len;
        while((len = is.read(buffer)) != -1){
            fos.write(buffer,0,len);
        }

        System.out.println("图片传输完成");

        //6.服务器端给予客户端反馈
        OutputStream os = socket.getOutputStream();
        os.write("你好,美女,照片我已收到,非常漂亮!".getBytes());

        //7.
        fos.close();
        is.close();
        socket.close();
        ss.close();
        os.close();

    }
}

Four, UDP network programming

1. Brief description

Class DatagramSocketand DatagramPacketimplemented based UDPprotocol network program.

UDPData reported by datagram sockets DatagramSocketto send and receive, the system does not guarantee that UDPpackets will be able to secure sent to the destination, we can not know when it arrived.

DatagramPacketObjects encapsulate UDPdata packets, comprising a transmitting side in the datagram IPaddress and port number and the receiver's IPaddress and port number

UDPEach datagram in the protocol gives complete address information, so there is no need to establish a connection between the sender and the receiver. It's like sending a parcel.

2. Common methods of DatagramSocket class

3. The use of DatagramSocket class

Process:

DatagramSocket versus DatagramPacket

Establish the sender and receiver

Build data package

Calls Sockettransmitted, receiving method

shut down Socket

Note: The sending end and the receiving end are two independent running programs

Code example:

public class UDPTest {

    //发送端
    @Test
    public void sender() throws IOException {

        DatagramSocket socket = new DatagramSocket();

        String str = "我是UDP方式发送的导弹";
        byte[] data = str.getBytes();
        InetAddress inet = InetAddress.getLocalHost();
        DatagramPacket packet = new DatagramPacket(data,0,data.length,inet,9090);

        socket.send(packet);

        socket.close();

    }
    //接收端
    @Test
    public void receiver() throws IOException {

        DatagramSocket socket = new DatagramSocket(9090);

        byte[] buffer = new byte[100];
        DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);

        socket.receive(packet);

        System.out.println(new String(packet.getData(),0,packet.getLength()));

        socket.close();
    }
}

Five, URL programming

URL(Uniform Resource Locator): Uniform resource locator, which represents the address of a resource on the Internet.

It is a specific URI, that URLcan be used to identify a resource, but also indicates how locate this resource.

Through URLour network can access a variety of resources on the Internet, such as the most common www, ftp sites. Browser by parsing a given URLfind the file or other resource on the Web

The basic structure of URL is composed of 5 parts: <Transmission Protocol>: //<Host Name>: <Port Number>/<File Name># Fragment Name? parameter list

E.g: http://192.168.1.100:8080/helloworld/indexjsp#a?username=shkstart&password=123

#Section name : the anchor point, such as reading a novel, directly locate the chapter

Parameter list format : parameter name=parameter value¶meter name=parameter value...

1. URL class

1.1 Constructor

In order to express URL, java.netthe class is implemented in URL. We can be initialized by a constructor below URLtarget

public URL(String spec): By a represents URLmay be configured to address a string URLobject. E.g:URL url = new URL("[http://www.baidu.com/](http://www.baidu.com/)");

public URL(URL context,String spec): Construct a URL object by base URL and relative URL

E.g: URL downloadeUrl = new URL(url,"download.html");

public URL(String protocol,String host,String file);

`` For example:new URL("http","[www.baidu.com](http://www.baidu.com)",80,"download.html");

public URL(String protocol,String host,int port,String file);

E.g:new URL("http","[www.baidu.com](http://www.baidu.com)",80,"download.html");

Note: The URLclass constructor declare an exception is thrown, this anomaly must be treated non-running, usually used try-catchto capture statement.

1.2 Method

  • public String getProtocol()Gets the URLprotocol name
  • public String getHost()Gets the URLhost name
  • public String getPort()Gets the URLport number
  • public String getPath()Get the URLfile path
  • public String getFile()Gets the URLfile name
  • public String getQuery()Gets the URLquery name

Code example

public class URLTest {

    public static void main(String[] args) {

        try {

            URL url = new URL("http://localhost:8080/examples/beauty.jpg?username=Tom");

//            public String getProtocol(  )     获取该URL的协议名
            System.out.println(url.getProtocol());
//            public String getHost(  )           获取该URL的主机名
            System.out.println(url.getHost());
//            public String getPort(  )            获取该URL的端口号
            System.out.println(url.getPort());
//            public String getPath(  )           获取该URL的文件路径
            System.out.println(url.getPath());
//            public String getFile(  )             获取该URL的文件名
            System.out.println(url.getFile());
//            public String getQuery(   )        获取该URL的查询名
            System.out.println(url.getQuery());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

    }
}

Example: Download via URL

public class URLTest1 {

    public static void main(String[] args) {

        HttpURLConnection urlConnection = null;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            URL url = new URL("http://localhost:8080/examples/beauty.jpg");

            urlConnection = (HttpURLConnection) url.openConnection();

            urlConnection.connect();

            is = urlConnection.getInputStream();
            fos = new FileOutputStream("beauty3.jpg");

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

            System.out.println("下载完成");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(urlConnection != null){
                urlConnection.disconnect();
            }
        }
    }
}