JAVA basis - Network Programming

Copyright: gitboy https://blog.csdn.net/weixin_40160543/article/details/89607750

Class InetAddress

This class represents an Internet Protocol (IP) address.

IP addresses are 32-bit or 128-bit unsigned number used by IP, which is a low-level protocol, UDP and TCP protocols are based on its construction. Architecture IP address by RFC 790: Assigned

Numbers RFC 1918:Address Allocation for Private InternetsRFC 2365:Administratively Scoped

IP MulticastRFC 2373:IP Version 6 Addressing

Architecture definition. Examples of IP comprising InetAddress

Address, may also contain the corresponding host name (host name depending on whether it is or has been configured to perform reverse host name resolution).

 

Network Programming three elements:

A: IP address

B: Port

C: Agreement

 

public class InetAddressDemo {
public static void main(String[] args) throws UnknownHostException {
// public static InetAddress getByName(String host)
// InetAddress address = InetAddress.getByName("liuyi");
// InetAddress address = InetAddress.getByName("192.168.12.92");
InetAddress address1 = InetAddress.getByName("172.16.102.58");
InetAddress[] address2 = InetAddress.getAllByName("172.16.102.58");
// 获取两个东西:主机名,IP地址
// public String getHostName()
// public String getHostAddress()
String name1 = address1.getHostName();
String ip1 = address1.getHostAddress();

for (InetAddress inetAddress : address2) {
System.out.println(inetAddress);
}

System.out.println(name1 + "---" + ip1);
}
}

 

IP Address:

Uniquely identifies the computer's network.

The computer can only recognize binary data, our IP address should be a binary data.

But then, we configured IP address does not binary, and why?

IP:192.168.1.100

Conversion: 1,100,000,010,101,000 0,000,000,101,100,100

If that is: 1,100,000,010,101,000 0,000,000,101,100,100 words.

If every time we re-class time to configure the IP address, remember it is more trouble.

Therefore, in order to facilitate showing the IP address, we put on each data byte of the IP address is converted to decimal and then separately represented by:

"Dotted decimal"

Composition IP address: network ID + host ID segment segment

Class A: The first segment network segment number + number of three segments after the segments host number

A network number: 256 * 256 * 256 = 16777216

Class B: front section II + segment number after the network host number segment Sec

A network number: 256 * 256 = 65536

Class C: Three segments before + after the network segment number section number section host

A network number: 256

Classification IP address:

A class 1.0.0.1 --- 127.255.255.254 (1) 10.XXX is a private address (private address that is not used on the Internet, is used in a local area network address) (2) 127.XXX are reserved address, used cycle testing.

Class B 128.0.0.1 --- 191.255.255.254 172.16.0.0 --- 172.31.255.255 is a private address. 169.254.XX is reserved addresses.

Class C 192.0.0.1 --- 223.255.255.254 192.168.XX is a private address

Class D 224.0.0.1 --- 239.255.255.254

Class E 240.0.0.1 --- 247.255.255.254

Two DOS command:

ipconfig to see the local ip address

ping followed by ip address. Test the unit communication between the designated ip address and if there are problems

Special IP addresses:

Loopback address of 127.0.0.1 (expressed native)

xxx255 broadcast address

xxx0 network address

The port number:

It identifies the program running.

Valid port: 65535 ~ 0, where 0 to 1024 for use by or reserved ports.

protocol:

Regular communication

UDP:

The data package

Data is limited

Connection is not established

high speed

Unreliable

TCP:

Establish a connection channel

Unlimited data

Slow

reliable

For example:

UDP: texting

TCP: call

 

Scoket

--java.net

-- --DatagramSocket

This class represents sockets for sending and receiving datagram packets.

- --DatagramPacket

This class represents a datagram packet.

Datagram packets are used to implement a connectionless packet delivery service. Each packet based only on information contained in the packet routed from one machine to another machine. Sent from one machine to another machine a plurality of packets may be routed differently, or may arrive in a different order. Packet delivery is not guaranteed.

 

UDP protocol to send data:

A: Creating the sender Socket object

B: Creating the data, and the data package

C: Socket object calling packet transmission method

D: release of resources

 public class SendDemo {
public static void main(String[] args) throws IOException {
// 创建发送端Socket对象
// DatagramSocket()
DatagramSocket ds = new DatagramSocket();

// 创建数据,并把数据打包
// DatagramPacket(byte[] buf, int length, InetAddress address, int port)
// 创建数据
byte[] bys = "hello,udp,我来了".getBytes();
// 长度
int length = bys.length;
// IP地址对象
InetAddress address = InetAddress.getByName("172.16.102.58");
// 端口
int port = 10010;
DatagramPacket dp = new DatagramPacket(bys, length, address, port);

// 调用Socket对象的发送方法发送数据包
// public void send(DatagramPacket p)
ds.send(dp);

// 释放资源
ds.close();
}
}

 

UDP protocol reception data:

A: Create the Socket object receiving end

B: creating a data packet (receptacle)

C: Socket object method calls receiving reception data

D: parse the data packets, and displayed on the console

E: release of resources

 

 public class ReceiveDemo {
public static void main(String[] args) throws IOException {
// 创建接收端Socket对象
// DatagramSocket(int port)
DatagramSocket ds = new DatagramSocket(10010);

// 创建一个数据包(接收容器)
// DatagramPacket(byte[] buf, int length)
byte[] bys = new byte[1024];
int length = bys.length;
DatagramPacket dp = new DatagramPacket(bys, length);

// 调用Socket对象的接收方法接收数据
// public void receive(DatagramPacket p)
ds.receive(dp); // 阻塞式

// 解析数据包,并显示在控制台  
// 获取对方的ip
// public InetAddress getAddress()
InetAddress address = dp.getAddress();
String ip = address.getHostAddress();
// public byte[] getData():获取数据缓冲区
// public int getLength():获取数据的实际长度
byte[] bys2 = dp.getData();
int len = dp.getLength();
String s = new String(bys2, 0, len);
System.out.println(ip + "传递的数据是:" + s);

// 释放资源
ds.close();
}
}

 

TCP protocol to send data:

A: Create a Socket object sender

If this step is successful, it means that the connection has been established successfully.

B: obtain an output stream, the write data

C: release of resources

TCP protocol to receive data:

A: Create the Socket object receiving end

B: listen for client connections. Socket object returns a corresponding

C: takes an input stream, the read data is displayed in the console

D: release of resources

 

 public class ClientDemo {
public static void main(String[] args) throws IOException {
// 创建Socket对象
Socket s = new Socket("192.168.12.92", 34567);

// 封装文本文件
BufferedReader br = new BufferedReader(new FileReader(
"InetAddressDemo.java"));
// 封装通道内的流
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
s.getOutputStream()));

String line = null;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
bw.flush();
}

br.close();
s.close();
}
}

 

-- --ServerSocket

This class implements server sockets. Server socket waits for requests arrive over the network. It is based on the request to perform some operation, then the result may be returned to the requester.

The actual work of the server socket by SocketImpl

Examples of implementation of the class. An application can change the socket factory that creates the socket implementation to configure itself to create sockets appropriate to the local firewall.

 

 

public class ServerDemo {
public static void main(String[] args) throws IOException {
// 创建服务器Socket对象
ServerSocket ss = new ServerSocket(34567);

// 监听客户端连接
Socket s = ss.accept();

// 封装通道内的流
BufferedReader br = new BufferedReader(new InputStreamReader(
s.getInputStream()));

String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}


s.close();
}
}

 

Socket communication network developed using

Network programming, is the most exposed to the use of network communication Socket development. In Java, mainly the following three implementations BIO, NIO, AIO.

Discrimination on these three concepts has been previously seemed to understand, but the expression is not very clear, the following to be a complete summary of Discrimination clear.

1. BIO way

First, I use a relatively simple language to explain:

BIO is blocking IO, each TCP connection comes in servers need to create a thread to handle the connection establishment and messages. If a blockage has occurred in the middle (such as establishing a connection, read data, obstruction occurs when writing data), thread blocking can occur, concurrent case, N N threads connections need to deal with.

The disadvantage of this approach is that: concurrency, low efficiency

 

 

2. NIO way

NIO is JDK1.4 proposed, or to use some popular words to explain the working principle of the NIO:

NIO is non-blocking IO, is based on event-driven thinking (Reactor threading model). Compared with BIO is, NIO use a thread to manage all of the Socket channel, which is based on Selector mechanism, when a query to the event (connection, accept the connection, reading and writing), will be forwarded to a different processing thread (handler) .

3. AIO way

AIO is JDK1.7 proposed, that is asynchronous IO. AIO uses Proactor mode. We should first of discrimination is the difference between the NIO and AIO:

(1) Notify the NIO occurs before Handler;

(2) AIO notification occurs after the processing of reading and writing correction, represents the correlation operation has been finished when the notification.

AIO during read and write operation, only need to call the appropriate read / write method, and passing CompletionHandler (when the processor operation is completed), the action is completed calls CompletionHandler. NIO notice that occur before action is readable and writable time, Selector discovered after notification of these events and call processing Handler,

The following presents a flowchart of Proactor mode:

 

Guess you like

Origin blog.csdn.net/weixin_40160543/article/details/89607750