Java高级程序设计

网络编程

Networking

Computers running on the Internet communicate to each other using either the Transmission Control Protocol (TCP) or the User Datagram Protocol (UDP).

When you write Java programs that communicate over the network, you are programming at the application layer.

https://docs.oracle.com/javase/tutorial/networking/overview/networking.html

基本概念

  • TCP (Transmission Control Protocol) is a connection-based protocol that provides a reliable flow of data between two computers.
  • UDP (User Datagram Protocol) is a protocol that sends independent packets of data, called datagrams, from one computer to another with no guarantees about arrival.
  • The TCP and UDP protocols use ports to map incoming data to a particular process running on a computer.
  • The Hypertext Transfer Protocol (HTTP), File Transfer Protocol (FTP), and Telnet are all examples of applications that require a reliable communication channel.

URL

URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet. For instance: http://example.com

  • Protocol identifier
  • Resource name
    • Host Name
    • Filename
    • Port Number
    • Reference

Reading Directly from a URL

public class URLReader {
    public static void main(String[] args) throws Exception {

        URL oracle = new URL("http://www.oracle.com/");
        BufferedReader in = new BufferedReader(
        new InputStreamReader(oracle.openStream()));

        String inputLine;
        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
        in.close();
    }
}

Connecting to a URL

try {
    URL myURL = new URL("http://example.com/");
    URLConnection myURLConnection = myURL.openConnection();
    myURLConnection.connect();
} 
catch (MalformedURLException e) { 
    // new URL() failed
    // ...
} 
catch (IOException e) {   
    // openConnection() failed
    // ...
}

Reading from a URLConnection

public class URLConnectionReader {
    public static void main(String[] args) throws Exception {
        URL oracle = new URL("http://www.oracle.com/");
        URLConnection yc = oracle.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                                    yc.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) 
            System.out.println(inputLine);
        in.close();
    }
}

Writing to a URLConnection

URL url = new URL("http://example.com/servlet/ReverseServlet");
URLConnection connection = url.openConnection();
connection.setDoOutput(true);

OutputStreamWriter out = new OutputStreamWriter( connection.getOutputStream());
out.write("string=" + stringToReverse);
out.close();

BufferedReader in = new BufferedReader( new InputStreamReader(connection.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
    System.out.println(decodedString);
}
in.close();

Sockets

URLs and URLConnections provide a relatively high-level mechanism for accessing resources on the Internet. Sometimes your programs require lower-level network communication, for example, when you want to write a client-server application.

To communicate over TCP, a client program and a server program establish a connection to one another. Each program binds a socket to its end of the connection. To communicate, the client and the server each reads from and writes to the socket bound to the connection.

Socket

A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent to.

Server listen

a server runs on a specific computer and has a socket that is bound to a specific port number.

The server just waits, listening to the socket for a client to make a connection request.

ServerSocket serverSocket =
                new ServerSocket(80));

Client connect

The client knows the hostname of the machine on which the server is running and the port number on which the server is listening. The client also needs to identify itself to the server so it binds to a local port number that it will use during this connection.

Socket echoSocket = new Socket(hostName, portNumber);

Server accept

If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bound to the same local port and also has its remote endpoint set to the address and port of the client. It needs a new socket so that it can continue to listen to the original socket for connection requests while tending to the needs of the connected client.

Socket clientSocket = serverSocket.accept();     

Client-server communication

The client and server can now communicate by writing to or reading from their sockets.

例子

https://docs.oracle.com/javase/tutorial/networking/sockets/examples/EchoClient.java

https://docs.oracle.com/javase/tutorial/networking/sockets/examples/EchoServer.java

https://tools.ietf.org/html/rfc862

多个客户端

But it's still blocking! And too many theads cause performance issues!

Thread Context Switch

https://en.wikipedia.org/wiki/Context_switch

http://tutorials.jenkov.com/java-concurrency/costs.html

https://eli.thegreenplace.net/2018/measuring-context-switching-and-memory-overheads-for-linux-threads/

https://blog.tsunanet.net/2010/11/how-long-does-it-take-to-make-context.html

Non-blocking I/O

With non-blocking I/O, we can use a single thread to handle multiple concurrent connections.

  • Buffer
  • Channel
  • Selector

Selector

Java NIO has a class called “Selector” that allows a single thread to examine I/O events on multiple channels. That is, this selector can check the readiness of a channel for operations, such as reading and writing.

Tutorial

https://medium.com/coderscorner/tale-of-client-server-and-socket-a6ef54a74763

https://github.com/arukshani/JavaIOAndNIO