Java Network programming

Source: Internet
Author: User
Tags file transfer protocol

The OSI model consists of 7 levels:

(1) Physical layers (physical layer)

The physical layer is the lowest layer of the OSI Reference Model, which uses transport media to provide physical connectivity to the data link layer. the function of the physical layer is to send and receive binary bitstream through the transmission medium.

(2) Data link layer

The data link layer serves the network layer, solves the communication problem between two neighboring nodes, and transmits the protocol data unit called the data frame.

(3) Network layer

The network layer serves the transport layer, and the transmitted protocol data units are called packets or groupings. The primary role of this layer is to solve the problem of how the packets are routed through each node.

(4) The transmission layer (Transport layer)

The role of the transport layer is to provide end-to-end reliable and transparent data transfer services for the upper layer protocol, including handling error control and flow control issues. This layer shields the details of the lower data communication to the high level, so that the high-level users can see only a host-to-host, user-controlled and reliable data path between the two transport entities.

The Protocol data Unit transmitted by the transport layer is called a segment or message.

(5) Session Layer

The primary function of the session layer is to manage and coordinate communication (dialogs) between various processes on different hosts, which is responsible for establishing, managing, and terminating the sessions between applications.

(6) Presentation layers (Presentation layer)

The presentation layer handles the representation of the data encoding that flows through the nodes to ensure that the information emitted by one system application layer is read out by the application layer of the other system. Data compression and encryption is one of the transformation capabilities that the presentation layer provides.

(7) Application tier (Application layer)

The application layer is the highest layer of the OSI Reference Model and is the interface between the user and the network. This layer uses the application to complete the application needs of network users, such as file transfer, e-mail and so on.

TCP/IP layered model:

(1) Network interface layer

The network interface layer includes protocols for collaborating on the transfer of IP data over existing network media. In fact, the TCP/IP standard does not define the functions corresponding to the ISO data link layer and the physical layer. Instead, it defines protocols such as Address Resolution Protocol (Resolution Protocol,arp), which provides the interface between the data structure of the TCP/IP protocol and the actual physical hardware.

(2) Network interconnect layer

The mesh layer corresponds to the network layer of the OSI seven-layer reference model. This layer contains IP protocol, RIP protocol (Routing information Protocol, routing Information Protocol), which is responsible for the packing, addressing and routing of data. It also includes the inter-Network Control Message Protocol (Internet Command message PROTOCOL,ICMP) to provide network diagnostic information.

(3) Transport layer

The transport layer corresponds to the transport layer of the OSI seven-layer reference model, which provides two types of end-to-end communication services. Where the TCP protocol (transmission Control Protocol) provides reliable data flow transport services, the UDP protocol (use Datagram Protocol) provides unreliable user datagram services.

(4) Application layer

The application layer corresponds to the application layer and the expression layer of the OSI seven-layer reference model. The Internet Application layer protocol includes finger, Whois, FTP (File Transfer Protocol), Gopher, HTTP (Hypertext Transfer Protocol), Telent (Remote terminal Protocol), SMTP (Simple Mail Transfer Protocol), IRC (Internet Relay session), NNTP (Network News Transfer Protocol) and so on.

Client and server:

The client is the initiator of the communication, and the server program passively waits for the client to distinguish the communication. The client and the server make up the application.

Whether a program is a client or a server determines the type of socket API it uses when it communicates with its peers (peer).

Socket:

A socket (socket) is an abstraction layer through which applications send and receive data. The main socket types in the TCP/IP protocol family are now stream sockets and datagram sockets. A TCP/IP socket is uniquely determined by an IP address, an end-to-end protocol (TCP or UDP protocol), and a port number.

TCP Socket Programming:

1. The server initializes a ServerSocket object that indicates that the communication will occur on that port;

2. The server calls the Accept () method of the ServerSocket class. The method waits until a client connects to the specified port on the server;

3. While the server waits, the client instantiates a socket object, specifying the server name and port number to connect to;

The constructor of the 4.Socket class attempts to connect the client to the specified server and port number, and if the communication is established, the client now has a socket object capable of communicating with the server;

5. On the server side, the Accept () method returns a reference to the new socket of the server that will connect to the client's socket.

1  PackageChap18;2 3 ImportJava.io.BufferedReader;4 ImportJava.io.BufferedWriter;5 Importjava.io.IOException;6 ImportJava.io.InputStreamReader;7 ImportJava.io.OutputStreamWriter;8 ImportJava.net.ServerSocket;9 ImportJava.net.Socket;Ten /* One * Service Side A  */   -  Public classServer { -      Public Static voidMain (string[] args)throwsIOException { theServerSocket Server =NewServerSocket (3001); -Socket socket =server.accept (); -         //Write -BufferedReader reader =NewBufferedReader ( +                 NewInputStreamReader (Socket.getinputstream ())); -         Char[] ch =New Char[100]; +         intLen =reader.read (CH); ASYSTEM.OUT.PRINTLN ("Receive Message from client:"); atSystem.out.println (NewString (CH, 0, Len)); -         //Read -BufferedWriter writer =NewBufferedWriter ( -                 NewOutputStreamWriter (Socket.getoutputstream ())); -Writer.write ("Hello I am a server"); - Writer.flush (); in         //Freeing Resources - reader.close (); to writer.close (); + socket.close (); - server.close (); the     } *}
1  PackageChap18;2 3 ImportJava.io.BufferedReader;4 ImportJava.io.BufferedWriter;5 Importjava.io.IOException;6 ImportJava.io.InputStreamReader;7 ImportJava.io.OutputStreamWriter;8 ImportJava.net.Socket;9 Importjava.net.UnknownHostException;Ten /* One * Client A  */ -  Public classClient { -      Public Static voidMain (string[] args)throwsunknownhostexception, IOException { theSocket socket =NewSocket ("127.0.0.1", 3001); -         //writing data to the server -BufferedWriter writer =NewBufferedWriter ( -                 NewOutputStreamWriter (Socket.getoutputstream ())); +Writer.write ("Hello server, I am client"); - Writer.flush (); +         //reading data from the server ABufferedReader reader =NewBufferedReader ( at                 NewInputStreamReader (Socket.getinputstream ())); -          -         Char[] ch =New Char[100]; -         intLen =reader.read (CH); -SYSTEM.OUT.PRINTLN ("Receive Message from server:"); -System.out.println (NewString (CH, 0, Len)); in writer.close (); - reader.close (); to socket.close (); +     } -}

Inter-socket communication: The InputStream and OutputStream properties of a socket are the means by which two computers communicate with each other.

UDP socket Programming:

Role:

A non-connection protocol that sends binary data from one computer to another computer. Here, the data is called a packet, which contains the destination server and port number to which the data will be sent.

Both the sender and receiver of the datagram package use the Java.net.DatagramSocket class to send and receive packets, respectively.

Constructors for the Datagramsocket class:

1.DatagramSocket (): Creates an Datagramsocket instance and binds the object to a native default IP address, a randomly selected port in all available ports in this computer.

2.DatagramSocket (int prot): Creates an Datagramsocket instance and binds the object to the native default IP address, specifying the port.

3.DatagramSocket (int port, inetaddress laddr): Creates an Datagramsocket instance and binds the object to the specified IP address, specifying the port.

You can create a Datagramsocket instance from any of the three constructors above, and then receive and send the data by using the following two methods:

Receive (Datagrampacket P): Receives datagrams from this datagramsocket.

Send (Datagrampacket p): Sends the datagram outward with the Datagramsocket object.

Constructors for the Datagrampacket class:

Two constructors that receive a datagram packet:

Datagrampacket (byte[] buf,int length): Creates a Datagrampacket object with an empty array, which is the object of receiving data from Datagramsocket.

   Datagrampacket (byte[] buf, int offset, int length): Creates a Datagrampacket object with an empty array and specifies that the received data is placed in the BUF array, starting with offset, up to length A byte.

Four constructors to send datagram packets:

Datagrampacket (byte[] buf, int length, inetaddress addr, int port): Creates a Datagrampacket object in an array containing data. The IP address and port are also specified when the Datagrampacket object is created-this determines the destination of the datagram.

Datagrampacket (byte[] buf, int length, socketaddress address): Similar to the previous constructor, but the receiver name and port number are stored in the socketaddress parameter.

Datagrampacket (byte[] buf, int offset, int length, inetaddress address, int port): Creates a Datagrampacket object for sending, Specifies that the send BUF array begins with offset, with a total length of bytes.

Datagrampacket (byte[] buf, int offset, int length,socketaddress address): Similar to the previous constructor, but the receiver name and port number are stored in the socketaddress parameter.

Receive packet:

1. Create a byte array that is large enough to store the data for the packets to be received;

2. Instantiate a Datagrampacket object using this byte array;

3.DatagramSocket is instantiated it is assigned to a port on the local host to which the socket is bound;

4. Call the Receive () method of the Datagramsocket class to pass the Datagrampacket object into the method, which will cause the execution thread to block until a datagram packet is received or a supermarket timeout is sent.

To send a message packet:

1. Create a byte array that is large enough to store the packet data to be sent and populate the array with that data;

2. Create a new Datagrampacket object that stores the byte array above, along with the server name and the recipient's port number;

3.DatagramSocket is instantiated it is specified that the socket is bound to the port of the local host;

the Send () method of the 4.DatagramSocket class is called, Incoming The Datagrampacket object.

Java Network programming

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.