Basic Java Learning (vi) Introduction to network programming

Source: Internet
Author: User

Basic knowledge:
1, OSI layered model and TCP/IP layered model correspondence relation

2, seven layer model and the corresponding relationship between the protocol
Network layer------------IP (interconnection protocol between networks)
Transport Layer------------TCP (Transmission Control Protocol), UDP (User datagram protocols)
Application tier------------Telnet (standard protocol and primary method for Internet Telnet service), FTP (Text Transfer Protocol), HTTP (Hypertext Transfer Protocol)

3. IP address and port number
1, the IP address is used to uniquely identify a communication entity in the network, the communication entity can be a host, can be a printer, or a router port. The packets that are transmitted in the IP-protocol network must be marked with an IP address.
2, the IP address uniquely identifies the communication entity, but a communication entity can have multiple communication programs to provide network services. This is the time to distinguish between specific communication programs by port. A communication entity cannot have two communication programs that use the same port number.

4. TCP and UDP
1, TCP is a connection-oriented guarantee reliable transmission protocol. With the TCP protocol transmission, a sequential error-free data stream is obtained. It can provide reliable data flow between two computers, and applications such as HTTP, FTP, Telnet need this reliable communication channel.
2, UDP is a non-connected protocol, each datagram is a separate information, including the full source address or destination address, it on the network with any possible path to the destination, as to reach the destination, the time to reach the destination and the correctness of the content is not guaranteed.

TCP and UDP differences:
1, reliable transmission is to pay the price, the correctness of the data content of the test will inevitably occupy the computer processing time and network bandwidth. Therefore, TCP transmission efficiency is not as high as UDP.
2, many applications do not need to ensure strict transmission reliability, such as video conferencing system, does not require video audio data is absolutely correct, as long as it can be coherent. So in these scenarios, it's more appropriate to use UDP.

5. URL
1, the URL object represents the Uniform Resource Locator, is a pointer to the Internet "resources". It is made up of protocol names, hosts, ports, and resources that meet the following formats:
Protocol://host:port/resourcename
http://www.crazyit.org/index.php
2. Some methods of URL object can access the resources of the URL:
String getFile (): Gets the resource name of the URL
String gethost (): Get host Name
String GetPath (): Get path part
int Getport (): Get port number
public static void Main (string[] args) throws IOException
{
URL url = new URL ("Https://i.cnblogs.com/EditPosts.aspx?opt=1");
String file = Url.getfile ();
String host = Url.gethost ();
int port = Url.getport ();
String query = Url.getquery ();
String protocol = Url.getprotocol ();
}
URL two most important methods: OpenConnection (), OpenStream ()
public static void Main (string[] args) throws IOException
{
URL url = new URL ("http://www.baidu.com");
URLConnection connection = Url.openconnection ();
InputStream is = Connection.getinputstream ();
OutputStream OS = new FileOutputStream ("C:/data.txt");
byte[] buffer = new byte[1024];
int flag = 0;
while ( -1! = (flag = is.read (buffer, 0, buffer.length)))
{
Os.write (buffer, 0, flag);
}
Os.close ();
Is.close ();
}

1, Code line 4th OpenConnection () This method is used to return the URLConnection object, which represents the remote connection to which the URL refers.
2, the Code line 5th getInputStream method, to return the input stream read from this open connection.
3, the following code is we are already familiar with reading from the input stream to the data, and then through the output stream to write to the file.
4, the implementation of the result is that we access through the browser http://www.baidu.com, Baidu server returned content.
5, here is a text file, we will change the suffix to HTML, and then use the browser to access, so it looks more intuitive:

6, InetAddress
Java provides the InetAddress class to represent an IP address.

public static void Main (string[] args) throws IOException
{
InetAddress address = Inetaddress.getlocalhost ();
SYSTEM.OUT.PRINTLN (address);
Address = Inetaddress.getbyname ("www.baidu.com");
SYSTEM.OUT.PRINTLN (address);

}
1 windows-ec813qq/192.168.88.1
2 www.baidu.com/115.239.211.112

7. Socket network communication
Socket, also known as socket, is the endpoint that connects two-way communication between two programs on the network.

The process of using a socket for network communication
Service side: The server program binds a socket to a specific port and waits and listens to the client's connection request through this socket.
Client: The client program makes a connection request based on the host name and port number where your server resides.
The communication between the two is done through the socket, we can think that the socket is a transport between the two cities, with it, you can travel between the two cities.

Host A's application communicates with Host B's application and must establish a connection through the socket, and a socket must be established by the underlying TCP/IP protocol to establish a TCP connection. Establishing a TCP connection requires the underlying IP protocol to address the hosts in the network. The IP address can only help us find the target host, but a host with multiple applications, how to find the application we need, this time can be specified by the port number.

Simple server side, client impersonation, sample:
Servers:
public class Servertest {
public static void Main (string[] args) throws IOException { br>//Create a ServerSocket to listen for the client socket connection Request
ServerSocket SS = new ServerSocket (9999);
SYSTEM.OUT.PRINTLN ("server Start");
//listens for requests by the client in a circular manner
while (true) {//listens for and accepts connections to this socket. This method is blocked until the connection is passed in.
Socket socket = ss.accept ();
//Get information about the client
InputStream is = Socket.getinputstream ();
BufferedReader br = new BufferedReader (new InputStreamReader (IS));
String str = br.readline ();
System.out.println (str);
//Send message to client
OutputStream OS = Socket.getoutputstream ();
PrintStream PS = new PrintStream (OS);
Ps.print ("Server-side client");
Ps.close ();
Os.close ();
Br.close ();
Is.close ();
Socket.close ();
}
}
}

Client:
public class client{
public static void Main (string[] args) throws Exception {
Socket socket = new socket ("localhost", 9999);
Sending information to the server
OutputStream OS = Socket.getoutputstream ();
PrintStream PS = new PrintStream (OS);
PS.PRINTLN ("Client-side services");
Read the information sent by the server
InputStream is = Socket.getinputstream ();
BufferedReader br = new BufferedReader (new InputStreamReader (IS));
String str = br.readline ();
System.out.println (str);
Br.close ();
Is.close ();
Socket.close ();
}

}

Basic Java Learning (vi) Introduction to 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.