I. Overview of network programming
Refers to the different geographical location of multiple computers with independent functions and their external devices, through the communication lines connected, in the network operating system, network management software and network communication Protocol management and coordination, to achieve the sharing of resources and information transmission computer system.
Network programming is used to realize the network interconnection between the different computers running on the computer can exchange data.
Some people say that the greatest inventions of the 20th century were not computers, but computer networks. Others say that if you buy a computer without networking, you buy a telephone without answering the phone line.
Second, the network model
The problem of network model research is the rules of communication between computer networks.
The network model generally refers to the OSI development Reference model and the TCP/IP reference model.
Network Reference Model Diagram
650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M01/8A/85/wKiom1gy2T6AVejuAAEDiPIZl-E242.png "title=" Small q-20161121192332.png "alt=" Wkiom1gy2t6avejuaaedipizl-e242.png "/>
Network Model 7 Layer Overview:
1. Physical Layer
The main definition of physical equipment standards, such as network cable interface type, optical fiber interface type, the transfer rate of various transmission media. Its main role is to transmit the bitstream (that is, 0 and 1 are converted to the current strength to transmit, to the destination and then into 0 and 1, which is what we often call the digital-to-analog conversion and ADC), the layer of data called bits.
2. Data Link layer: The main data received by the physical layer to the MAC address (the address of the network card) encapsulation and encapsulation. This layer of data is often called a frame. The device that works on this layer is the switch, which transmits the data through the switch.
3. Network layer: The data received by the lower level is mainly encapsulated and encapsulated with IP address. The devices that work on this layer are routers, which often call this layer of data a packet.
4. Transport Layer: Defines a number of transmission data protocol and port number, such as TCP protocol, low transmission efficiency, high reliability, for transmission reliability requirements, data volume of data; UDP, for pure reliability requirements are not high, data volume small data, such as QQ chat data is transmitted in this way.
5. Session Layer: The path of data transmission through the transport layer, mainly to initiate a session between the system or accept the session request.
6. Expression: The main is to carry out the interpretation of the received data, encryption and decryption, compression and decompression, and so on.
7. Application layer: Mainly refer to some interrupts. such as QQ, FTP and so on.
Three elements of network programming
IP Address: The identity of the device in the network, not easy to remember, the host name can be
PORT: The logical address used to identify the process, different process identities
Transport protocol: TCP, UDP
Iv. IP Address
To allow computers in the network to communicate with each other, you must specify an identification number for each computer, the identification number to specify the computer to receive the data and the computer that identifies the send, in the TCP/IP protocol, the flag number is the IP address. In short,an IP address is a unique identifier for a computer on the network.
The computer can only recognize binary data, so our IP address should be a binary data, but, in fact, the IP address we configured is not binary data, why?
Example: IP address 192.168.1.100
Conversion 11000000 10101000 00000001 01100100
But, too long, so, for the convenience of memory, we will convert the data on each byte of the IP address into decimal, and then use. Separate to represent.
IP Address Composition: Network number segment + host number segment
Class a 1.0.0.1---127.255.255.254
Class b 128.0.0.1---191.255.255.254172.16.0.0---172.31.255.255 is a private address. 169.254.X.X is a reserved address.
Class c 192.0.0.1---223.255.255.254192.168.x.x is a private address
Class D 224.0.0.1---239.255.255.254
Class e 240.0.0.1---247.255.255.254
(1) 10.x.x.x is a private address (the private address is not used on the Internet, but is used in the local area network address)
(2) 127.x.x.x is a reserved address for use as a cyclic test.
To facilitate our acquisition and operation of IP addresses, Java provides the InetAddress class for our use.
Package Cn3;import java.net.inetaddress;/** * If a class has no constructor method * 1. All members are static * 2. Single example * 3. There is a static method that returns an instance of this class * */public class Ine Taddressdemo {public static void main (string[] args) throws exception{//gets an IP address object by host name inetaddress net = Inetaddress.getbyname ("localhost");//Gets the host name and host address of the IP address object string hostName = Net.gethostname (); String address = net.gethostaddress ();//Output IP address object corresponding hostname and host address System.out.println ("hostname:" +hostname+ ", host Address:" +address);}}
Host name: localhost, host address: 127.0.0.1
Five, port number
Physical Port Nic Port
Logical port What we're talking about is the logical port.
Each network program will have at least one logical port.
The logical address used to identify the process, with different identities for different processes.
Valid ports: 0-65535, where 0-1024 systems use or retain ports
Vi. Agreement
UDP: The data source and destination are encapsulated into a packet, there is no need to establish a connection, the size of each packet is limited to 64k, because there is no connection, is unreliable protocol, do not need to establish a connection, fast.
TCP: Establishes the connection, forms the channel which transmits the data, carries on the big data quantity transmission in the connection, completes the connection through the three times handshake, is the reliable agreement, must establish the connection, therefore, the efficiency is relatively low.
Seven, Socket
Socket socket: A combination of IP addresses and port numbers that have a unique identity on the network can form a uniquely identifiable identifier socket.
Socket principle Mechanism:
Sockets are available in all two segments of the communication.
Network communication is actually the communication between sockets.
Data is transmitted via IO between two sockets.
Eight, UDP send and receive data
package cn3;import java.io.ioexception;import JAVA.NET.DATAGRAMPACKET;IMPORT JAVA.NET.DATAGRAMSOCKET;IMPORT JAVA.NET.INETADDRESS;/* *UDP sending data */public class senddemo {public static void main (String[] args) THROWS IOEXCEPTION {//1. Create a UDP object that sends data datagramsocket socket = new datagramsocket (); //the destination address of the sending data inetaddress net = inetaddress.getbyname ("localhost");//Port number Int port = 10000;//sent data byte[] b = "Hello, world!" ". GetBytes ();//The length of the data sent INT LEN = B.LENGTH;//2. Encapsulates the address + port + data into a packet so that the UDP send object is sent///from which we can see that UDP is an unreliable protocol, it will address + port + data encapsulated together to send,//so that the receiving party to get the packet, and then parse the packet, but we can not ensure that the receiver will receive this packet, in case of loss datagrampacket p = new datagrampacket (B, len, net,port);//3. Send packet Socket.send (p);//4. Releasing Resources Socket.close ( );}}
Package Cn3;import Java.io.ioexception;import Java.net.datagrampacket;import Java.net.datagramsocket;public class Getdemo {public static void main (string[] args) throws IOException {//1. Create a UDP object that accepts data datagramsocket socket = new Datagram Socket (10000);//2. Define a packet to receive data byte[] b = new Byte[1024];int len = B.length;datagrampacket p = new Datagrampacket (b, Len); The 3.UDP object receives the data and exists in the packet defined above socket.receive (p);//data from the packet byte[] data = P.getdata (); int length = P.getlength (); System.out.println (New String (data,0,length));//4. Release Resource Socket.close ();}}
Of course, we have to start the receiving end, so that it is waiting, once the sender is started, then the receiving side will understand the receiving packet, and parse the packet, and then both the receiving and sending end of the thread shutdown.
Code simplification
package cn4;import java.io.ioexception;import java.net.datagrampacket;import java.net.datagramsocket;public class getdemo {public Static void main (String[] args) throws ioexception {// The sensor receives data from the socket object Datagramsocket ds = new datagramsocket (10087);//Create a packet byte[] b =  NEW BYTE[1024];D atagrampacket p = new datagrampacket (b, b.length);// Receive Data ds.receive (p);//Parse Data string address = p.getaddress (). gethostaddress (); String str = new string (P.getdata (), 0,p.getlength ()); SYSTEM.OUT.PRINTLN ("Get Data from" +address+: "+str);//Release Resource Ds.close ();}}
Package Cn4;import Java.io.ioexception;import Java.net.datagrampacket;import java.net.datagramsocket;import Java.net.inetaddress;public class Setdemo {public static void main (string[] args) throws IOException {// Create a Sender Socket object Datagramsocket ds = new Datagramsocket ();//Create Data and package byte[] b = "Hello, world!" ". GetBytes ();D atagrampacket p = new Datagrampacket (b, B.length,inetaddress.getbyname (" localhost "), 10087);// Send packet Ds.send (p);//Release Resource Ds.close ();}}
IX. TCP sends and receives data
PACKAGE CN5;/** * TCP protocol receives data * 1. Creating a Socket object on the receiving end * 2. Listens for client connections and returns a corresponding socket object * 3. Gets the input stream, reading the data displayed in the console * 4. Freeing Resources * */import java.io.IOException;import java.io.InputStream;import Java.net.serversocket;import java.net.socket;public class getdemo {public static void main (String[] args) throws ioexception {serversocket serversocket = new serversocket (12307); Socket socket = serversocket.accept ();inputstream inputstream = Socket.getinputstream (); Byte[] b = new byte[1024];int len = 0 ;while (( Len=inputstream.read (b)) != -1) {System.out.println (new string (B,0,len));} Socket.close ();}}
Package Cn5;import Java.io.ioexception;import Java.io.outputstream;import java.net.inetaddress;import java.net.socket;/** * TCP Send Data * 1. Create a Socket object for the sender * This step, if successful, indicates that the connection has been established successfully * 2. Get the output stream, write Data * 3. Release resources */public class Senddemo {PU Blic static void Main (string[] args) throws IOException {//Create the socket object of the sender///This can be seen that TCP first to connect with the server, if the sending side first started, there will be an exception "three handshake"// Exception in thread "main" java.net.ConnectException:Connection refused:connectsocket socket = new Socket (INETADDRESS.G Etbyname ("localhost"), 12307);//Get output stream OutputStream OutputStream = Socket.getoutputstream ();//write Data Outputstream.write ( "Hello". GetBytes ());//Release Resources socket.close ();}}
This article is from the "11831428" blog, please be sure to keep this source http://11841428.blog.51cto.com/11831428/1875561
Java Network programming