Dark Horse programmer------Java Network Programming Learning Summary

Source: Internet
Author: User

Java training, Android training, iOS training,. NET training </a>, look forward to communicating with you!

Network model: 

OSI Reference Model

TCP/IP Reference Model

Network Reference Model Diagram

Elements of network communication :

IP Address: inetaddress

Identification of devices in the network

Not easy to remember, can use host name

Local loopback address: 127.0.0.1; host name: localhost

Port number

The logical address used to identify the process, and the identity of the different processes

Valid ports: 0~65535, where 0~1024 uses ports or reserved ports for the system

Network protocol

is a rule of network communication

Common protocols: TCP,UDP

Udp:

1, the data and the source and destination encapsulated in the packet, do not need to establish a connection

2. Limit the size of each packet within 64K

3, because there is no connection, so is unreliable agreement

4, do not need to establish a connection, so faster

Tcp:

1. Establish a connection to form a channel for transmitting data

2, in the connection of large data volume transmission

3, through the three-time handshake to establish a connection, is a reliable protocol

4, because the connection must be established, so the transmission efficiency is slightly lower

Socket:

1, socket is to provide a mechanism for network services. Commonly known as sockets, the equivalent of a plug.

2. There are sockets on both ends of the communication

3, network communication is actually the communication between sockets

4. Data is transmitted via IO between two sockets

5, in the network transmission, the sending side/client and the receiving end/service side is usually two independent running programs.

UDP Transport:

1. Two objects required: Datagramsocket and Datagrampacket

2, set up the sending side, the receiving end

3. Set up the data package

4, call the socket send, accept method

5. Close the socket.

  Send side:

On the sending side, specify the destination IP and port number in the object in the packet

  Receiving end:

The receiving end should explicitly specify the port to listen on

code example:

Importjava.net.*;/*Requirement: Send a piece of text data through the UDP transmission mode. Defines a UDP send side. Idea: 1, establish updsocket service. 2, provide data, and encapsulate the data in a packet. 3, through the socket service send function, the packet is sent out. 4, close the resource. */classudpsend{ Public Static voidMain (string[] args)throwsexception{//1, create the UDP service. Through the Datagramsocket object. Datagramsocket ds =NewDatagramsocket (8888); //2. Identify the data and encapsulate it into a packet. Datagrampacket (byte[] buf, int length, inetaddress address, int port)        byte[] buf = "udp ge men lai le". GetBytes (); Datagrampacket DP=NewDatagrampacket (Buf,buf.length,inetaddress.getbyname ("192.168.1.254"), 10000); //3, through the socket service, the existing data packets sent out. Through the Send method. Ds.send (DP); //4, close the resource. Ds.close (); }}/*Requirements: Define an application to receive and process data transmitted by the UDP protocol. Defines the receive side of UDP. Idea: 1, define Udpsocket service. A port is typically monitored. is to define a digital ID for this receiving network application. It is easy to define what data comes up to the application to handle. 2, define a packet, because the received byte data is to be stored. Because there are more features in the packet object, you can extract different data information from the byte data. 3, the received data is stored in a defined packet via the Receive method of the socket service. 4, through the unique features of the packet object. Take these different data out. Print on the console. 5, close the resource. */classudprece{ Public Static voidMain (string[] args)throwsexception{//1, create the UDP socket and set up the endpoint. Datagramsocket ds =NewDatagramsocket (10000);  while(true){        //2. Define the packet. Used to store data.         byte[] buf =New byte[1024]; Datagrampacket DP=NewDatagrampacket (buf,buf.length); //3, the received data is stored in the packet via the Receive method of the service. Ds.receive (DP);//blocking method. //4, the data is obtained through the method of the packet. String IP =dp.getaddress (). gethostaddress (); String Data=NewString (Dp.getdata (), 0, Dp.getlength ()); intPort =Dp.getport (); SYSTEM.OUT.PRINTLN (IP+ "::" +data+ "::" +port); }        //5, close the resource, (optional)//ds.close ();    }}

TCP Transport:

1. Required objects: Sockets and ServerSocket

2. Establish client and server side

3, after establishing the connection, through the IO stream in the socket for data transmission

4. Close socket

  Client basic idea:

* The client needs to specify the IP address and port of the server so that it can try to establish a connection, and if the connection fails, an exception occurs.

* The connection is successful, indicating that the client and the server have established a channel, then the data can be transmitted through IO stream.

The *socket already provides the output stream and the input stream object, which can be obtained through the getInputStream () and Getoutputstream () methods.

* After the data transfer with the server, close the socket.

  Service-side Basic ideas:

* The server needs to be clear on which port it is going to process the data.

* When there is client access, it needs to be clear which client. The client object to access is obtained through the Accept () method, and the data is transmitted through the IO stream through the object and the client

* When the client access is complete, close the client.

code example:

/ * Demo TCP transport. 1,TCP client and service side.  2, the client corresponding to the object is the socket. The object that corresponds to the server is ServerSocket. The *//* client, by looking up the socket object, discovers that when the object is established, it can connect to the specified host. Because TCP is connection-oriented. Therefore, in the establishment of the socket service, there must be a server exists, and the connection is successful. After the pathway is formed, the data is transmitted in the channel. Requirement: Sends a text data to the server. Step: 1, create the socket service. and specify the host and port to connect to. */Import Java.io.*;import java.net.*;class tcpclient{public static void Main (string[] args) throws Exception {//Create the client socket service. Specify destination host and PortSocket s = new socket ("192.168.1.254", 10003);//In order to send data, you should get the output stream in the socket stream. OutputStream out = S.getoutputstream (), Out.write ("tcp ge Men lai le". GetBytes ()); S.close (); }}/* Requirements: Define the endpoint to receive data and print it on the console. Server: 1, set up the socket service side. ServerSocket (), and listen for a port. 2. Gets the client object that is connected. Through Serversokcet's Accept method. No connection will wait, so this method is blocking. 3, if the client sends the data, then the server will use the corresponding client object and fetch the read stream to the client object to read the data sent. and print it in the console. 4, close the server. (optional) */Class tcpserver{public static void Main (string[] args) throws exception{//Set up a service-side socket service. And listen for a port. ServerSocket ss = new ServerSocket (10003);//Get the client object connected through the Accept method. while (true) {Socket s = ss.accept ();  String IP = s.getinetaddress (). gethostaddress (); System.out.println (ip+ "... connected");//Get the data sent by the client, then use the read stream of the client object to read the data. InputStream in = S.getinputstream ();  byte[] buf = new byte[1024];  int len = In.read (BUF);  System.out.println (New String (Buf,0,len)); S.close ();//Close the client.}//ss.close ();}}

The most likely problem with TCP transmission:

  1, the client and the server after the connection, both sides are waiting, there is no data transmission.

The reason is that both the read () method and the ReadLine () method are blocking methods.

  2, the solution:

1. Custom end tag

2, using Shutdowninput and Shutdownoutput method.

Practice:

Requirements: Establish a text conversion server. The client sends text to the server, and the service order converts the text to uppercase in return to the client. And the customer degree can continue to do text conversion. When the client enters over, the conversion ends.

/*
Analysis: The client: Since it is manipulating the data on the device, you can use IO technology and think according to the operational rules of IO. Source: Keyboard entry. Purpose: Network device, network output stream. It also operates on text data. You can select a character stream. Step 1, set up the service. 2, get keyboard entry. 3. Send the data to the server. 4, then go back to the server to return the uppercase data. 5, end, close resources. */ImportJava.io.*;Importjava.net.*;classtransclient{ Public Static voidMain (string[] args)throwsexception{Socket S=NewSocket ("192.168.1.254", 10005); //defines a stream object that reads the keyboard data. BufferedReader BUFR =NewBufferedReader (NewInputStreamReader (system.in)); //defines the purpose of writing data to the socket output stream. Sent to the service side. //BufferedWriter bufout =//New BufferedWriter (New OutputStreamWriter (S.getoutputstream ()));PrintWriter out =NewPrintWriter (S.getoutputstream (),true); //defines a socket read stream that reads the uppercase information returned by the server. BufferedReader Bufin =NewBufferedReader (NewInputStreamReader (S.getinputstream ())); String Line=NULL; while((Line=bufr.readline ())! =NULL){ if("Over". Equals (line)) Break; Out.println (line);//Bufout.write (line);//bufout.newline ();//Here if there is no newline tag, it will cause both ends to wait//Bufout.flush ();String str=Bufin.readline (); System.out.println ("Server:" +str); } bufr.close (); S.close (); }}/*server: Source: Socket read stream. Purpose: the socket output stream. It's all text and decorations. */classtransserver{ Public Static voidMain (string[] args)throwsexception{ServerSocket SS=NewServerSocket (10005); Socket s=ss.accept (); String IP=s.getinetaddress (). gethostaddress (); SYSTEM.OUT.PRINTLN (IP+ ".... Connected"); //reads the data from the socket read stream. BufferedReader Bufin =NewBufferedReader (NewInputStreamReader (S.getinputstream ())); //purpose. Socket output stream. Writes uppercase data to the socket output stream and sends it to the client. //BufferedWriter bufout =//New BufferedWriter (New OutputStreamWriter (S.getoutputstream ()));PrintWriter out=NewPrintWriter (S.getoutputstream (),true); String Line=NULL; while((Line=bufin.readline ())! =NULL) {System.out.println (line); Out.println (Line.touppercase ());//Bufout.write (Line.touppercase ());//bufout.newline ();//Bufout.flush ();} s.close (); Ss.close (); }}

Dark Horse programmer------Java Network Programming Learning Summary

Related Article

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.