Java. Network programming

Network programming

Overview of network programming

C/S and B/S

C/S:

The client server software structure, and the content that the service provider needs to prepare for the user's service

  1. Clients of major platforms
    Android iOS PC Windows Linux macOS
    QQ wechat Taobao JD sword and expedition
  2. Server provides services
    Software update:
    The version of the LOL server is updated, and the local software is also updated. This operation is very time-consuming.
    This kind of update belongs to hot update.

B/S:

Browser server software structure, as long as the service provider provides data services, it is OK, and the front-end data display mode

  1. Browser providers are very, very many
    Google, Firefox, Auburn, Safari, Edge
  2. Server provides services
    Software update:
    The server updates the data, and the browser refreshes.

Network communication protocol

protocol: protocol Protocol

Network communication protocol is required to be abided by by the computers that both sides transmit data according to the corresponding network transmission protocol,
Only then can you enter the data interaction and transmission.

At present, UDP and TCP/IP are common protocols for data transmission in network segments.

Difference between UDP and TCP/IP

UDP

  1. For connectionless, data transmission is not particularly secure
  2. Because of no connection, fast transmission speed
  3. Because of no connection, packet loss exists in data transmission
  4. UDP has no difference between client and server. It can be used as sender and receiver

UDP protocol usage scenario: live broadcast, online game

TCP/IP

  1. Connection oriented, safe data transmission
  2. All transfers are slow because of connection oriented
  3. Connection oriented, data transmission guaranteed
  4. TCP/IP protocol has a clear concept of server and client

TCP/IP protocol usage scenarios: client login, data download, file transfer.

Three elements of network programming

1. agreement

Two is that the computer data transmission in the network situation needs the corresponding protocol to complete.

2.IP address (Internet Protocol Address)

An address number of the current computer in the network, similar to a mobile phone number

IP address has IPv4 protocol and IPv6 protocol

IPv4 is a 32-bit binary number, usually the display effect is a.b.c.d for example: 192.168.1.1
a.b.c.d represents 0 ~ 255 numbers, which has consumed 4.2 billion at present.

IPv6 is to ensure that every grain of sand on earth has an IP address.
128 bit address length, set of 16 bytes, set of 8 0x0 ~ 0xFFFF

3. port number

The port number is a number in the computer for the current application. It can let the computer know,
The current data is given to which program, or from which program the data appears.

Port number is a short type 0 ~ 65535

0 ~ 1024 cannot be used for custom port number. Specific system port number

Class IP

The IP address class provided by SUN company for development: InetAddress

Common methods:
InetAddress getLocalhost();

Get native IP address class object

InetAddress getByName(String str);

Get the corresponding IP address object according to the specified host name

InetAddress[] getAllByName(String str);

Gets the specified host name or all IP address class objects corresponding to the domain name

Method demo code example:

import java.net.InetAddress;
import java.net.UnknownHostException;
/*
* IP Class demonstration
*/
public class Demo1 {
	public static void main(String[] args) throws
		UnknownHostException {
		InetAddress localHost = InetAddress.getLocalHost();
		System.out.println(localHost);
		InetAddress byName = InetAddress.getByName("DESKTOP-M89SDP7");
		System.out.println(byName);
		InetAddress byName2 = InetAddress.getByName("www.4399.com");
		System.out.println(byName2);

		System.out.println("----------------------------------");	
		InetAddress[] allByName = InetAddress.getAllByName("www.baidu.com");
		for (InetAddress inetAddress : allByName) {
			System.out.println(inetAddress);
		}
		System.out.println("----------------------------------");
		
		InetAddress[] allByName1 = InetAddress.getAllByName("www.taobao.com");
		for (InetAddress inetAddress : allByName1) {
			System.out.println(inetAddress);
		}
	
		System.out.println("----------------------------------");
		InetAddress[] allByName2 = InetAddress.getAllByName("www.jd.com");
		for (InetAddress inetAddress : allByName2) {
			System.out.println(inetAddress);
		}
	}
}

UDP protocol data transmission

UDP data transmission mode

User Datagram Protocol

Data transmission adopts the method of data package. All data shall be packaged and there is no corresponding
 Client server concept, with and only sending segment and receiving terminal. 

Socket socket
Data needs to be transferred. There must be a corresponding Socket between the two computers for data transfer. If UDP protocol is adopted here, there must be a Socket of UDP protocol.
DatagramSocket();

Create a sender UDP protocol Socket object

DatagramSocket(int port);

Create a Socket object of the UDP protocol of the receiver. Here, you need to [listen] to specify the port

Package method of sending end data package:

DatagramPacket DatagramPacket(byte[] buf, int length, InetAddress address, int port);

buf: byte array to pass data
length: is the number of data capacity bytes in the current byte array
Address: IP address object of receiver
Port: port number corresponding to the receiver

Receiving method of receiving terminal packet: an empty packet needs to be prepared here

DatagramPacket DatagramPacket(byte[] buf, int length);

buf: byte buffered array, usually 1024 integer times
length: the capacity of the current byte buffer array

Sending end

Technological process:

  1. Create the corresponding sending Socket of UDP server
  2. Prepare corresponding data package with specified data
  3. send data
  4. Close UDP sender

Code example:

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/*
Technological process:
1. Create the corresponding sending Socket of UDP server
2. Prepare corresponding data package with specified data
3. send data
4. Close UDP sender
*/
public class SenderDemo1 {
	public static void main(String[] args) throws IOException {
		System.out.println("Transmitter start");
		// Create the corresponding Socket
		DatagramSocket socket = new DatagramSocket();
		// Prepare package
		byte[] bytes = "Steamed lamb for lunch today...".getBytes();
		DatagramPacket packet = new DatagramPacket(
								bytes, // Byte array data
								bytes.length, // Byte array data length
								InetAddress.getLocalHost(), //Specify the IP address of the receiver
								8848); // 8848 corresponding port number
		// Send packet
		socket.send(packet);
		// Close UDP sender
		socket.close();
	}
}

receiving end

Technological process:

  1. Open UDP service and listen for the specified port
  2. Create a new empty package
  3. Receive data through Socket
  4. Close UDP service receiver

Code example:

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
/*
Technological process:
 - Open UDP service and listen for the specified port
 - Create a new empty package
 - receive data through Socket
 - Close UDP service receiver
*/
public class ReceiveDemo1 {
	public static void main(String[] args) throws
		IOException {
		// Create Socket listening port
		DatagramSocket socket = new DatagramSocket(8848);
		// Prepare empty packets
		byte[] buf = new byte[1024];
		DatagramPacket packet = new DatagramPacket(buf, buf.length);
		// receive data
		socket.receive(packet);
		// Determine the length of bytes received
		int length = packet.getLength();
		System.out.println(new String(buf, 0, length));
		// Close socket
		socket.close();
	}
}

UDP data transmission loss

  • The network is not good enough, the stability is not good enough, and the bandwidth is not enough
  • Poor computer performance

FeiQ

Network transmission has its own transmission specification. If the data received by the software is its own specification, it can read the data, if not, it can be discarded.

FeiQ:

version:time:sender:ip:flag:content
Version: time: sender name: sender IP: tag: content

The data is of String type, and the protocol used is UDP protocol.

Example of sending message code to feiQ:

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class FeiQ {
	public static void main(String[] args) throws
		IOException {
		DatagramSocket socket = new DatagramSocket();
		String data = getData("Welcome to Java World!!!");
		DatagramPacket datagramPacket = new DatagramPacket(data.getBytes(),
		data.getBytes().length , InetAddress.getByName("192.168.31.255"), 2425);
		socket.send(datagramPacket);
		socket.close();
	}
/**
* Incoming data, converted to data recognized by FeiQ
* version:time:sender:ip:flag:content
*
* @param message String type content
* @return FeiQ compliant string
*/
	public static String getData(String message) {
		StringBuilder stb = new StringBuilder();
		stb.append("1.0:");
		stb.append(System.currentTimeMillis() + ":");
		stb.append("Anonymous:");
		stb.append("10.1.1.1:");
		stb.append("32:");
		stb.append(message);
		return stb.toString();
	}
}

TCP

Compared with UDP, TCP is a stable transport protocol. There are three handshakes to ensure the connection status. At the same time, there are clear differences between the client and the server.
In the TCP service, the server needs to start first, listen to the specified port, and wait for the client to connect.

The client actively connects to the server. Only after connecting with the server can the data be exchanged. The server cannot actively connect to the client.

For TCP operations, Java provides two sockets

  1. Server Socket
    java.net.ServerSocket;
    Create the corresponding serverticket to open the server and wait for the client to connect
  2. Client Socket
    java.net.Socket
    Create the client score, connect to the server, and send the Socket to the server binding registration.

Socket - client socket

Provide the Socket object conforming to TCP/IP requirements for data transmission to the client.

Constructor:

Socket(String host, int port);

host is the IP address of the server, and port corresponds to the port number of the server program
 Gets the TCP connection object through the specified server IP address and port number.

Member Method:
InputStream getInputStream();

Get the input byte stream of Socket object, and get the corresponding data from the server
 InputStream is a resource and needs to close Read when the program exits

OutputStream getOutputStream();

Get the output byte stream of Sokcet object and send the data to the server
 OutputStream is a resource that needs to be closed when the program exits

void close();

Close client Socket

void shutdownOutput();

Disable the current Socket from sending data

The Socket corresponding to TCP/IP protocol is implemented by IO flow.

ServerSocket - server Socket

Open Socket server on server side

Constructor:
ServerSocket(int port);

Open the ServerSocket server and specify who the current service port is

Member Method:
Socket accept();

Listen and connect to get a Socket object, which is a blocking method,
Will be in a listening state all the time.

It returns the Socket, that is, the client Socket object. It gets the current Socket object,
Relative to getting the connection to the client, the Socket used at the same time is the same as the client.

TCP protocol code demonstration

Server code

Technological process:

  1. Create a ServerSocket server and listen to the specified port at the same time
  2. Get Socket connection through accept method and get client Socket object
  3. Get InputStream through Socket object and read data sent by client
  4. Through the Socket object, get the OutputStream and send the data to the client
  5. Shut down service

Code example:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/*
Technological process:
1. Create a ServerSocket server and listen to the specified port at the same time
2. Get Socket connection through accept method and get client Socket object
3. Get InputStream through Socket object and read data sent by client
4. Through the Socket object, get the OutputStream and send the data to the client
5. Shut down service
*/
public class TcpServer1 {
	public static void main(String[] args) throws
		IOException {
		System.out.println("Server start");
		System.out.println("-----------------------");
		// 1. Create a ServerSocket server and listen to the specified port at the same time
		ServerSocket serverSocket = new ServerSocket(8848);
		// 2. Get Socket connection through accept method, and get client Socket object
		Socket socket = serverSocket.accept();
		// 3. Get InputStream through Socket object and read the data sent by client
		InputStream inputStream = socket.getInputStream();
		// IO flow operation
		byte[] buf = new byte[1024];
		int length = inputStream.read(buf);
		System.out.println(new String(buf, 0, length));
		// 4. Get the OutputStream through the Socket object and send the data to the client
		OutputStream outputStream = socket.getOutputStream();
		String str = "Welcome to the Deley Alliance";
		outputStream.write(str.getBytes());
		// 5. Close the Socket service and the input byte stream and output byte stream used by the current Socket
		// Closing this socket will also closethe socket's InputStream and OutputStream.
		socket.close();
	}
}

Client code

Technological process:

  1. Create a Socket service and specify the IP address and corresponding port number of the connected server
  2. Obtain the corresponding OutputStream object through the Socket object and send the data to the server
  3. Through the Socket object, obtain the corresponding InputStream object and receive the data sent by the server
  4. Shut down service

Code example:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
/*
Technological process:
1. Create a Socket service and specify the IP address and corresponding port number of the connected server
2. Obtain the corresponding OutputStream object through the Socket object and send the data to the server
3. Through the Socket object, obtain the corresponding InputStream object and receive the data sent by the server
4. Shut down service
*/
public class TcpClient1 {
	public static void main(String[] args) throws
		UnknownHostException, IOException {
		System.out.println("Client start");
		System.out.println("------------------------");
		// 1. Create a Socket service and specify the IP address and corresponding port number of the connected server
		Socket socket = new Socket("192.168.31.154", 8848);
		// 2. Get the corresponding OutputStream object through the Socket object and send the data to the server
		OutputStream outputStream = socket.getOutputStream();
		outputStream.write("Hello server!!!".getBytes());
		// 3. Obtain the corresponding InputStream object through the Socket object, and receive the data sent by the server
		InputStream inputStream = socket.getInputStream();
		byte[] buf = new byte[1024];
		int length = inputStream.read(buf);
		System.out.println(new String(buf, 0, length));
		// 4. Close service
		socket.close();
	}
}

File upload operation

Analysis process

Client program

Technological process:

  1. Create the input byte stream operation of the corresponding file, where the buffer can be used
  2. Start Socket,
  3. Get Socket output OutputStream object and send data to the server
  4. Side reading
  5. When the file reading is finished and the sending is finished, close the client
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
/*
Technological process:
1. Create the input byte stream operation of the corresponding file, where the buffer can be used
2. Start Socket,
3. Get Socket output OutputStream object and send data to the server
4. Side reading
5. When the file reading is finished and the sending is finished, close the client
*/
public class TcpClient {
	public static void main(String[] args) throws
		IOException {
		// 1. Create the input byte stream operation of the corresponding file, where buffer can be used
		BufferedInputStream bis = new BufferedInputStream( new FileInputStream(new File("D:/aaa/1.mp4")));
		// 2. Start Socket
		Socket socket = new Socket(InetAddress.getLocalHost().getHostAddress(), 8848);
		// 3. Get Socket output OutputStream object and send data to the server
		OutputStream outputStream = socket.getOutputStream();
		int length = -1;
		byte[] buf = new byte[1024 * 8];
		// 4. Read and send data
		while ((length = bis.read(buf)) != -1) {
			outputStream.write(buf, 0, length);
		}
		// 5. Close resources
		socket.close();
		bis.close();
	}
}

Server program

Technological process:

  1. Start the server service and create the ServerSocket object
  2. Specify the location to save the file and create the output buffer byte stream of the corresponding folder
  3. Read data, write file
  4. Shut down the server
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
/*
Technological process:
1. Start the server service and create the ServerSocket object
2. Specify the location to save the file and create the output buffer byte stream of the corresponding folder
3. Read data, write file
4. Shut down the server
*/
public class TcpServer {
	public static void main(String[] args) throws
		IOException {
		// 1. Start the server service and create the ServerSocket object
		ServerSocket serverSocket = new ServerSocket(8848);
		Socket socket = serverSocket.accept();
		// 2. Specify the location to save the file, and create the output buffer byte stream of the corresponding folder
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("D:/aaa/temp.mp4")));
		// 3. Obtain the input stream corresponding to the Socket
		InputStream inputStream = socket.getInputStream();
		// 4. Reading and writing
		int length = -1;
		byte[] buf = new byte[1024 * 8];
		while ((length = inputStream.read(buf))!= -1) {
			bos.write(buf, 0, length);
		}
		// 5. Close resources
		bos.close();
		socket.close();
	}
}
Published 16 original articles, won praise 5, visited 404
Private letter follow

Keywords: socket Java network Programming

Added by prasitc2005 on Fri, 13 Mar 2020 15:47:30 +0200