Network protocol (UDP and TCP protocol summary)

Source: Internet
Author: User


First, the Knowledge Reserve:

1. Three elements of network communication:

IP Address: inetaddress

Identification of devices in the network

Hard to remember, host name available

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 the 0~1024 system uses or retains ports.

Note: Not the so-called physical port!

Transport protocol

Rules of Communication

Common protocols: TCP,UDP

Features of the 2.UDP and TCP protocols:

UDP:

1. Encapsulate the data source and destination into a packet without establishing a connection
2, the size of each packet is limited to less than 64k
3, because no connection, is unreliable agreement
4, does not need to establish the connection, the speed is fast

Example: Chat, walkie-talkie is UDP, for no connection (whether in the absence, know, just send, speed), lost data also no matter. Fast speed. Data is divided into packages

Tcp:

1. Establish a connection to form a channel for transmitting data
2, the transmission of large amounts of data in the connection
3, through the three-time handshake to complete the connection, is a reliable protocol
4, must establish the connection, the efficiency will be slightly lower

Example: telephone calls, must be connected, the other party agrees to send the data (otherwise wait), can not lose data.

3. IP object in Java: InetAddress.

InetAddress: Construction method Private, cannot create object directly.

Inetaddressgetbyname (String host): Determines the IP address of the host, given the host name.

Inetaddressgetlocalhost (): Returns the local host.

Inetaddress[]getallbyname (String host)

Ip.gethostaddress (),

Ip.gethostname ()

4. Socket (socket, network endpoint)

A socket is a mechanism that is provided for network services.

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.

Second, the transmission of UDP and the receiving end of the transfer:

1.UDP Send side:

1, set up UDP socket service, if there is no explicit port when creating object,

A port that is not used is automatically assigned to the system.

2, specify the specific data to be sent.

3, the data is encapsulated into a packet.

4, send the data packets with the Send method of the socket service.

5, close the resource.

Import java.net.*;

Class udpsend{

public static void Main (string[] args) throws Exception {

1, set up a UDP socket service.

Datagramsocket ds = Newdatagramsocket (8888);//Specifies the send port, and does not specify that the system is randomly assigned.

2, specify the specific data to be sent.

String text = "UDP transmission demo buddy came";

byte[] buf = Text.getbytes ();

3, the data is encapsulated into a packet.

Datagrampacket DP = Newdatagrampacket (BUF,

Buf.length,inetaddress.getbyname ("10.1.31.127"), 10000);

4, send the data packets with the Send method of the socket service.

Ds.send (DP);

5, close the resource.

Ds.close ();

}

}

2.UDP Receiving end:

1. To create a UDP socket service, it is necessary to specify a port, the function is that only the data sent to this port is the data that the receiving end can process.

2. Define the packet that is used to store the received data.

3. The received data is stored in a packet via the socket service's Receive method.

4. Get the specific data content in the packet by the method of the packet,

such as IP, port, data, and so on.

5. Close the resource.

Import java.net.*;

Class Udprece {

public static void Main (string[] args) throws exception{

///1, create a UDP socket service.

Datagramsocket ds = Newdatagramsocket (10000);//must be specified, and the same as the port number above!

///2, defines the packet that is used to store the received data. The byte array is defined first, and the packet stores the data in a byte array.

byte[] buf = new byte[1024];

Datagrampacket DP = Newdatagrampacket (BUF,BUF.LENGTH);

///3, the received data is stored in a packet via the socket service's Receive method.

Ds.receive (DP);//The method is a blocking method.

///4, the data packet to obtain the specific data content in the packet, such as IP, port, data and so on.

String IP =dp.getaddress (). gethostaddress ();

int port = Dp.getport ();

string text = NewString (Dp.getdata (), 0,dp.getlength ());//Convert valid portions of a byte array to a string.

System.out.println (ip+ ":" +port+ "--" +text ");

///5, close the resource.

Ds.close ();

}

}

Third, the TCP client and the service side of the transmission

1.TCP Client:

1, the establishment of TCP socket service, it is best to specify the specific address and port. When this object is created, it is already possible to connect to the specified IP and port (three handshake).

2, if the connection is successful, it means that the channel is established, the socket flow has been generated. As long as you get the read stream and write stream to the socket stream, you can get two stream objects through getInputStream and Getoutputstream.

3, close the resources.

Import java.net.*;

Import java.io.*;

Requirement: The client sends a data to the server side.

Class tcpclient{

public static void Main (string[] args) throws exception{

Socket s = newsocket ("10.1.31.69", 10002);

OutputStream out = S.getoutputstream ();// Gets the output stream object in the socket stream.

Out.write ("TCP demo, Buddy comes Again!"). GetBytes ());

S.close ();

}

}

2.TCP Service side:

1, create the service-side socket service and listen to a port.

2, the server in order to provide services to the client, get the contents of the client, you can get the client object connected through the Accept method.

3, you can communicate by getting the socket stream in the socket object and the specific client.

4, if the communication is over, close the resource. Note: To close the client first, then close the server.

Class tcpserver{

public static void Main (string[] args) throws exception{

ServerSocket ss = new ServerSocket (10002);//Socket Service set up for server

Socket s = ss.accept ();//Get Client Object

String IP =s.getinetaddress (). gethostaddress ();

System.out.println (ip+ "... connected");

You can communicate with a specific client by getting the socket in the socket object.

InputStream in = S.getinputstream ();//Read the client's data, using the client object's socket read stream

byte[] buf = newbyte[1024];

int len = In.read (BUF);

String Text = newstring (Buf,0,len);

System.out.println (text);

If the communication ends, close the resource. Note: To first close the client, on the off service side.

S.close ();

Ss.close ();

}

}

Summarize

For network programming, it is important to understand the steps, according to the needs of the step by step to build the foundation!

Client and server need to interact, then build the corresponding stream, for its input and output!

For the blocking method, be sure to note that the stop tag is provided!

For PrintWriter, remember to use println instead of write; do not forget to add true, auto Refresh!

Network protocol (UDP and TCP protocol summary)

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.