Dark Horse programmer ———— Network Programming in Java

Source: Internet
Author: User

------<a href= "http://www.itheima.com" target= "blank" >java training, Android training, iOS training,. NET training </a>, look forward to communicating with you! -------

Network programming in Java I. Network programming Overview: Internet-based programmingIs the data exchange between programs running on different computers that are used to implement network interconnection.


Two. Network model: OSI and TCP/IP1.OSI (Open System Interconnection interconnect) Reference ModelNetwork Model 7 Layer Overview:
1). Physical layer: The main definition of physical equipment standards, such as the interface type of the network cable, the interface type of optical fiber, the transmission rate of various transmission media. Its main role is to transmit the bitstream (that is, 1, 0 is converted to the current strength to carry out the transmission, after reaching the destination in the conversion to 1, 0, that is, we often say the digital-to-analog conversion and A/D conversion). This layer of data is called a bit.
2). Data Link layer: The package and solution of the MAC address (the address of the network card) is mainly the data received from the physical layer. 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 Package and solution encapsulation of IP address (example 192.168.0.1) is mainly the data received from the lower level. The device that works on this layer is the router, which is often called the data packet.
4). Transport Layer: Defines a number of protocols and port numbers for transmitting data (WWW port 80, etc.), such as: TCP (Transmission Control Protocol, low transmission efficiency, strong reliability, high transmission reliability requirements, data volume data), UDP (User Datagram Protocol, the opposite of TCP characteristics, For transmission reliability requirements are not high, data volume of small data, such as QQ chat data is transmitted in this way. The main point is to segment and transmit the data received from the lower layer, and then reorganize after reaching the destination address. This layer of data is often called a segment.
5). Session Layer: A path for data transmission through the Transport Layer (port number: Transport port and receive port). Primarily initiates a session between your systems or accepts a session request (the device needs to know each other either IP or Mac or hostname)
6). Presentation layer: The main is to carry on the interpretation of the received data, encryption and decryption, compression and decompression, etc. (that is, the computer can recognize something that adults can recognize things (tablets, sounds, etc.).
7). Application layer: Mainly some terminal applications, such as FTP (all kinds of file download), WEB (ie browsing), QQ and so on (it can be understood as we can see on the computer screen things. is the terminal application).


2.TCP/IP Reference ModelApplication layer, Transport layer, internetwork layer, host to network layer




Three. Three elements of network programming:1.IP Address:1). The so-called IP address is a 32bit address assigned to each host connected to the Internet.
2). In accordance with the TCP/IP rules, IPs are represented by binary, each IP address is 32bit long and bits are converted into bytes.
is a 4 byte. For example, a binary form of IP address is "11000000101010000000000101100100", so long address,
People are too laborious to deal with it. In order to facilitate people's use, IP addresses are often written in decimal form, using symbols in the middle "." Separate the different bytes. So
The above IP address can be represented as "10.0.0.1". This notation of IP addresses is called "Dotted decimal notation", which is obviously much easier to remember than 1 and 0.
Example: 192.168.1.10 (dotted decimal)
Binary representation: 11000000.10101000.00000001.00001010
Each paragraph uses 8 bits of binary, altogether four paragraphs, altogether 32 bits are represented.
Indicates the range:
Min ip:00000000.00000000.00000000.00000000--Decimal means: 0.0.0.0
Max ip:11111111.11111111.11111111.11111111--Decimal means: 255.255.255.255
So the range of each segment: 0--255: altogether 256.
Total can accommodate: 256 * 256 * 256 * 256 computers;
3). The composition of the IP address:
IP address = network number + host address

Class A IP address: The first number is the network number, the remaining three segment number is the local computer's number: 192.0.0.0:Range: 192.0.0.0--192.255.255.255:256 * 256 * 256 units
Class B IP Address: The first two segment number is the network number, the remaining two segment number is the local computer's number: 192.168.0.0:Range: 192.168.0.0--192.168.255.255:256 * 256 units
Class C IP Address: The first three segment number is the network number, the remaining part number is the local computer's number: 192.168.1.0:Scope: 192.168.1.0--192.168.1.255:256 Station

Role:
The following are three IPs:
1). 192.168.1.10;
2). 192.168.1.20;
3). 192.168.2.30;

Can you access each of the above three IP addresses? is determined by the subnet mask: it is used to differentiate between "network number" and "host address".
If the subnet mask is set to: 255.255.255.0
Binary: 11111111.11111111.11111111.00000000
In the subnet mask, all marked as 1 is "network number", the above mask means: the first three paragraphs are "network number", the first three paragraphs of the same IP, in a network segment, you can exchange visits;
1) and 2) may exchange visits;

If the subnet mask is set to: 255.255.0.0
Binary: 11111111.11111111.00000000.00000000
The above subnet mask, all marked as 1 "network number", the first two paragraphs are "network number", the first two paragraphs in the same network segment, you can exchange visits;
1) and 2) and 3) can be exchanged for visits;



Special Address: 127.0.0.1 loopback address, which can be used to test whether there is a problem with the local network. Ping 127.0.0.1
DOS command ipconfig: view native IP address

xxx.xxx.xxx.0 Network Address
xxx.xxx.xxx.255 Broadcast Address


Class A 1.0.0.1---127.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.
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



2. Port; Identifies the logical address of the process and the identity of the different processes1). Classification:
Physical port: Network card port;
Logical port: is maintained by the operating system. Mapping a physical port to multiple "logical ports" for use by multiple network programs;
2). The port we are talking about is the "logical port";
3). Under window, maintain 65,536 logical ports, port number: 0--65535
4). A network program to receive network data, at least one port is used, and is "exclusive during runtime". An application can use multiple logical ports at the same time;
A port can serve only one program at a time. cannot be used by multiple programs at the same time.
5). The logical port range within Windows is: 0--65535, where: 0--1024 is used internally by the system, we try not to use; we try to use more than 1024


3. Protocol; Rules of communication, common protocols: TCP,UDP1). Agreement: The Parties agree on certain content, the purpose is to enable both parties to do things as agreed;
2). "Protocol" in the network programming, it means: The format of the information sent by both parties and the format of the other's parsing data;
3). Ftp,http,udp,tcp and so on;
4). UDP Features:
1. Package the data sent;
2. For no connection, when sending, do not care whether the other party receives.
3. The size of each datagram is limited to 64k;
4. Because there is no need to connect, therefore: unreliable. But the speed is fast;
For example: Radio stations, television stations to send signals;
5). TCP Features:
1. When sending, a connection must be established. The receiver must exist, otherwise it cannot be sent;
2. Because of the need to establish a connection, so: reliable. But the speed (connection speed) will be relatively slow, because some connection verification;
For example: Call

Four. Inetadddress class--To obtain an IP address1. Get the object:

Because this class does not have a constructor method, it can use its internal static method

public static inetaddress Getbyname (String host): Parameter: Host-the specified master, or null. Returns: The IP address of the given host name.
2. Member Methods:Public String gethostname (): Gets the host name;
Public String gethostaddress (): Get IP Address

public class Demo {public static void main (string[] args) {try {//Get all host names within the same LAN for (int i=0;i<256;i++) {String str= "19 2.168.36. "+i;inetaddress add=inetaddress.getbyname (str);//str can be an IP address, or it can be a hostname string name=add.gethostname (); String ip=add.gethostaddress (); System.out.println (name+ "---" +ip);}} catch (Unknownhostexception e) {}}}




Five. Socket sockets1. A uniquely identified IP address and port number on the network can be combined to form a uniquely identifiable identifier socket2.Socket principle Mechanism:Sockets are available at both ends of the communication.
Network communication is actually the communication between sockets
Data is transmitted via IO between two sockets.


Six. UDP implementation1. Send side:
Datagramsocket socket = new Datagramsocket (); byte[] ByteArray = "Hello". GetBytes (); inetaddress IP = Inetaddress.getbyname (" LENOVO-PC "); int port = 8888;datagrampacket Pak = new Datagrampacket (bytearray,bytearray.length,ip,port); Socket.send ( Pak); Socket.close ();


2. Receiving End:
Datagramsocket socket = new Datagramsocket (8888); byte[] ByteArray = new byte[1024];D atagrampacket pak = new Datagrampacket (bytearray,bytearray.length); socket.receive (Pak); byte[] ByteArray2 = Pak.getdata (); String info = new String (Bytearray2,0,pak.getlength ()); System.out.println ("received message:" + info); Socket.close ();



3. Send data for UDP protocol:Steps:
1. Instantiate the Socket:datagramsocket object; Datagramsocket () constructs a datagram socket and binds it to any available port on the local host.
2. Ready to send the information:
1). Send the information;
2). IP of the target computer;
3). Port of the target computer;
3. Encapsulates a Datagram object: Datagrampacket object: Constructs a datagram package that is used to send a length-long package to a specified port number on the specified host. The length parameter must be less than or equal to buf.length.
4. Send the datagram using the socket; socket object. Send (Packet object)


public class Demo {public static void main (string[] args) throws exception{//send data for UDP protocol// Create Datagramsocket Object Datagramsocket socket=new datagramsocket (); String str= "Hello dear";//Create InetAddress Object inetaddress adress=inetaddress.getbyname ("MyComputer");//DECLARE port int port=8888;/ /encapsulates the packet object Datagrampacket pack=new datagrampacket (Str.getbytes (), Str.getbytes (). Length,adress,port);// Send packet Socket.send (pack) using socket; SYSTEM.OUT.PRINTLN ("Data Sent");//Release Resource Socket.close ();}}





4. Receive UDP protocol data:Steps:
1). Establish a connection using the socket: Datagramsocket
2). Prepare an empty byte[] array to store the received data.
3). Instantiate an empty datagram object, waiting for data sent by the sending side;
4). Once the data is sent, parse the data;

public class Udpreceive {public static void main (string[] args) throws exception{//create Datagramsocket object, receive data, create with port number, To use the same port number as the sending port Datagramsocket socket=new datagramsocket (8888);//Prepare an empty byte array, store data byte[] bytearray=new byte[1024];// Using an empty array, create an empty packet object to receive the data Datagrampacket pack=new datagrampacket (ByteArray, bytearray.length); System.out.println ("Waiting to receive data!! ");//Receive Data socket.receive (Pack), where the program will block ★★★★system.out.println (" Receive data!! "); /Parse Data//Use byte array, get data packet information byte[] Byte1=pack.getdata (); String Str=new string (Byte1,0,pack.getlength ());//Use the length of the packet instead of the length of the array System.out.println (str);//Get the IP and host name of the other side of the string IP =pack.getaddress (). gethostaddress (); ★★★//note the type returned here is String name=pack.getaddress (). GetHostName (); System.out.println ("The other IP address is:" +ip+ "the host name of the object is:" +name);//Release Resource Socket.close ();}}




5. A few major pointsThe pack.getaddress () return value is of type inetaddress and can obtain information about the host.
Byte[] Byte1=pack.getdata (); The data in the sent packet can be fetched into the array
Pack.getlength () returns the number of bytes of data in the packet
Receiving end (3 steps)
Datagramsocket socket=new Datagramsocket (8888); for the receiver's socket, use the port name to define
Datagrampacket pack=new datagrampacket (ByteArray, bytearray.length); Use an empty byte array to define a packet at the receiving end
Socket.receive (pack); Receive packets. In fact, the data in the object is loaded into the packet, each receive will be re-loaded, the loop, to continue to pack to


Send side (3 steps)
Datagramsocket socket=new Datagramsocket (); Defines the socket of the sender using the null-parameter construction method
Datagrampacket pack=new Datagrampacket (Str.getbytes (), Str.getbytes (). Length,adress,port), using arrays containing data, and array lengths, and destination address and port number to define the packet
Socket.send (pack); Send packets. Loop, you must constantly send a packet to create a new package.




Five. TCP implementations:1. Send side:
<span style= "White-space:pre" ></span>socket socket = new Socket ("127.0.0.1", 8888); OutputStream out = Socket.getoutputstream (); Out.write ("Hello". GetBytes ()); Out.close (); Socket.close ();


2. Receiving End:
<span style= "White-space:pre" ></span>serversocket server = new ServerSocket (8888); Socket socket = server.accept (); InputStream in = Socket.getinputstream (); byte[] ByteArray = new Byte[1024];int len = in.re AD (ByteArray); String info = new string (Bytearray,0,len); System.out.println ("Received information:" + info); In.close (); Socket.close (); Server.close ();




3.TCP sending dataSteps:
1). Instantiate a socket object, use: IP of the destination computer, port
2). To send data, from the socket object, get an "output stream";
3). Send data;
4). Releasing resources;


Note: TCP is connection-oriented, so you must first start the "Receive Side"
public class Tcpsend {public static void main (string[] args) throws exception{//use the IP address and port of the destination host to create a socket object socket soc= New socket ("127.0.0.1", 8888);//Use the Get socket object to get a byte output stream reference OutputStream Out=soc.getoutputstream ();/ Writes the data using the output stream to write out Out.write ("We are going Today". GetBytes ());//Close Resource out.close (); Soc.close (); SYSTEM.OUT.PRINTLN ("Send data Complete");}}




4. Receive data:
1. Instantiate a serversocket: use port;
2. Wait for connection: Seversocket-->accept ();
¡ï ★ 3. If there is a client connection, the Accept () method returns and returns a Socket object that is the socket of the client
the corresponding relationship;
4. Because the client sends the data first, this side must first receive the data. Reads data from the network.
Gets an "input stream".
5. Read the data;
6. Release of resources;
public class Tcpreceive {public static void main (string[] args) throws Exception {//Use port number, instantiate a Serversocketserversocket Server=new ServerSocket (8888);//wait for data input System.out.println ("Wait for Client Connection");//define a socket reference, waiting for the client to connect to the socket socket= Server.accept ();//The program here blocks SYSTEM.OUT.PRINTLN ("Client Connection");//parse the data//from the resulting socket object will be an input stream from the network to get InputStream in= Socket.getinputstream ();//define a byte array byte[] bytearray=new byte[1024];//Read the data in the input stream int num=in.read (byteArray); String Str=new string (bytearray,0,num); System.out.println (str);//Release Resources in.close (); Socket.close ();}}


5. Note:Send side: (3 steps)
Socket soc=new socket ("127.0.0.1", 8888);//create object with destination IP address and port name
OutputStream Out=soc.getoutputstream ();//create an output stream using the socket object
¡ï ★ Out.write ("We're leaving Today". GetBytes ());//write out the data outward. Cycle, you have to constantly write out.
Receiving end: (4 steps)
ServerSocket server=new ServerSocket (8888);//Create an object using the same port as the send port
Socket socket=server.accept (), program blocking waits for client to connect, ☆★★★★//just waits for customer to connect
InputStream in= Socket.getinputstream ();//Read the data in the socket into the program
★ int Num=in.read (ByteArray),////To read the data in the input stream//loop, the data is continuously read into the array through the input stream, without the need for the front. It's time to refresh constantly



Black Horse Programmer ———— Network programming in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.