Use of InetAddress class
1, Two problems to be solved in realizing network communication
- 1. How to accurately locate one or more hosts on the network; Locate a specific application on the host
- 2. How to transmit data reliably and efficiently after finding the host
2, Two elements of network communication:
- 1. Corresponding question 1: IP and port number
- 2. Corresponding question 2: provide network communication protocol: TCP/IP reference model (application layer, transport layer, network layer, physical + data link layer)
3, Communication element 1: IP and port number
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: www.baidu.com com www.mi. com www.sina. com www.jd. com
Domain name resolution: the domain name is easy to remember. When you enter the domain name of a host when connecting to the network, the domain name server(DNS)Responsible for converting domain names into IP Address in order to establish a connection with the host. -------Domain name resolution
-
- Local loop address: 127.0 0.1 corresponds to localhost
2.InetAddress class: an object of this class represents a specific IP address
2.1 instantiation
getByName(String host) , getLocalHost()
2.2 common methods
getHostName() / getHostAddress()
3. Port number: the process running on the computer.
- Requirements: different processes have different port numbers
- Range: specified as a 16 bit integer 0 ~ 65535.
The combination of port number and IP address yields a network Socket: Socket
4, Communication element 2: network communication protocol
- Typing model
2. Differences between TCP and UDP
3. Three handshakes and four waves
TCP network programming
Code example 1: the client sends information to the server, and the server displays the data on the console
//Client
@Test
public void client() {
Socket socket = null;
OutputStream os = null;
try {
//1. Create a Socket object to indicate the ip and port number of the server
InetAddress inet = InetAddress.getByName("192.168.14.100");
socket = new Socket(inet,8899);
//2. Gets an output stream for outputting data
os = socket.getOutputStream();
//3. Operation of writing out data
os.write("Hello, this is client mm". getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
//4. Resource shutdown
if(os != null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
} if(socket != null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } //Server @Test public void server() { ServerSocket ss = null; Socket socket = null; InputStream is = null; ByteArrayOutputStream baos = null; try { //1. Create a ServerSocket on the server side and indicate its own port number ss = new ServerSocket(8899); //2. Call accept() to receive the socket from the client socket = ss.accept(); //3. Get input stream is = socket.getInputStream(); //It is not recommended to write in this way. It may be garbled
// 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. Read data from input stream
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("Received from:" + socket.getInetAddress().getHostAddress() + "Data"); } catch (IOException e) { e.printStackTrace(); } finally { if(baos != null){ //5. Close resources 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(); } } } }
Code example 2: the client sends a file to the server, and the server saves the file locally.
/*
The exceptions involved here should be handled with 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();
}
/*
The exceptions involved here should be handled with 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();
}
Code example 3: send files from the client to the server, and the server saves them locally. And return "send successfully" to the client. And close the corresponding connection.
/*
The exceptions involved here should be handled with 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);
}
//Turn off data output
socket.shutdownOutput();
//5. Receive data from the server and display it on the console 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();
}
/*
The exceptions involved here should be handled with 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("Picture transfer complete"); //6. The server gives feedback to the client OutputStream os = socket.getOutputStream(); os.write("Hello, beauty, I have received the photo. It's very beautiful!".getBytes()); //7. fos.close(); is.close(); socket.close(); ss.close(); os.close();
}
UDP network programming
Code example:
//Sender
@Test
public void sender() throws IOException {
DatagramSocket socket = new DatagramSocket(); String str = "I am UDP Missile sent by"; byte[] data = str.getBytes(); InetAddress inet = InetAddress.getLocalHost(); DatagramPacket packet = new DatagramPacket(data,0,data.length,inet,9090); socket.send(packet); socket.close();
}
//Receiving end
@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();
}
URL programming
1. Understanding of URL (uniform resource locator):
The uniform resource locator corresponds to a resource address on the Internet
2. Five basic structures of URL:
- http://localhost:8080/examples/beauty.jpg?username=Tom
- Protocol hostname port number resource address parameter list
3. How to instantiate:
URL url = new URL("http://localhost:8080/examples/beauty.jpg?username=Tom");
4. Common methods:
5. You can read and download the corresponding url resources:
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("day10\\beauty3.jpg"); byte[] buffer = new byte[1024]; int len; while((len = is.read(buffer)) != -1){ fos.write(buffer,0,len); } System.out.println("Download complete"); } catch (IOException e) { e.printStackTrace(); } finally { //close resource 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(); } }
}