JavaSE- network programming (TCP programming, UDP programming, URL)

1. TCP / IP protocol suite

  • Transport Protocol There are two very important protocols:
    Transmission Control Protocol TCP (Transmission Control Protocol)
    user datagram protocol UDP (User Datagram Protocol). TCP / IP its two main protocols: transmission control protocol (TCP) and Internetworking Protocol (IP) is named, is actually a set of protocols, including a plurality of protocols having different functions and interrelated.
  • IP (Internet Protocol) network layer protocol is the main protocol to support the data communications internetworking.
  • TCP / IP protocol model from a more practical point of view, forming a four-layer architecture efficient, i.e. a physical link layer, IP layer, transport layer and application layer.

1.1 TCP protocol

Before using the TCP protocol, must first establish a TCP connection, form a transmission channel data
before transmission, a "three-way handshake" mode, point to point communication, reliable
two application processes TCP protocol for communication: the client, the server.
Connection can be transmitted in a large amount of data
transfer is completed, the need to release an established connection, inefficiency
Here Insert Picture Description

Here Insert Picture Description

1.2 UDP protocol

Data, source and destination encapsulation into packets, without establishing a connection
the size of each packet is limited to 64K
sent regardless of whether the other party is ready, the recipient does not receive a confirmation, it is not reliable
can broadcast transmitting
transmission data At the end of the resource without releasing small overhead, fast

1.3 Socket

  • The use of socket (Socket) to develop web applications has long been widely adopted, so that a de facto standard.
  • A combination of IP address and port number on the network with a unique identifier together to constitute a unique identifier to identify the socket.
  • The ends of the communication must have Socket, the endpoint of communication between two machines.
  • In fact, network traffic is communication between the Socket.
  • Socket program allows the network connection as a stream, data transmission between the two IO Socket.
  • General initiates communication application is a client waits for the server communication requests.
  • Socket Category:
    stream socket (stream socket): using TCP byte stream to provide dependable service
    datagram socket (datagram socket): using UDP provides "best effort" datagram service
  • Socket class constructor common:
public Socket(InetAddress address,int port)创建一个流套接字并将其连接到指定 IP 地址的指定端口号。 
public Socket(String host,int port)创建一个流套接字并将其连接到指定主机上的指定端口号。
  • Socket class common method:
public InputStream getInputStream()返回此套接字的输入流。可以用于接收网络消息
public OutputStream getOutputStream()返回此套接字的输出流。可以用于发送网络消息
public InetAddress getInetAddress()此套接字连接到的远程 IP 地址;如果套接字是未连接的,则返回 null。 
public InetAddress getLocalAddress()获取套接字绑定的本地地址。 即本端的IP地址
public int getPort()此套接字连接到的远程端口号;如果尚未连接套接字,则返回 0public int getLocalPort()返回此套接字绑定到的本地端口。 如果尚未绑定套接字,则返回 -1。即本端的端口号。 
public void close()关闭此套接字。套接字被关闭后,便不可在以后的网络连接中使用(即无法重新连接或重新绑定)。需要创建新的套接字对象。 关闭此套接字也将会关闭该套接字的 InputStream 和OutputStream。 
public void shutdownInput()如果在套接字上调用 shutdownInput() 后从套接字输入流读取内容,则流将返回 EOF(文件结束符)。 即不能在从此套接字的输入流中接收任何数据。 
public void shutdownOutput()禁用此套接字的输出流。对于 TCP 套接字,任何以前写入的数据都将被发送,并且后跟 TCP 的正常连接终止序列。 如果在套接字上调用 shutdownOutput() 后写入套接字输出流,则该流将抛出 IOException。 即不能通过此套接字的输出流发送任何数据。

2. Based on the TCP Socket Programming

  • Based on the programming language Java socket into the server program and client program, the communication model shown in Figure:
    -Here Insert Picture Description

2.1 client creates a Socket object

  • Socket client work process includes the following four basic steps:
  1. Creating Socket: based on IP address or port number specified object constructor Socket class service side. If the response to the server, the client to establish a communication line to the server. If the connection fails, there will be an exception.
  2. Socket opening connected to the input / outflow: using the getInputStream () method to obtain the input stream, using
    the getOutputStream () method to obtain the output stream, data transmission
  3. Socket according to a certain protocol for read / write operations: read the server by placing the information in the input stream line (but not read information into its own line), information is written by the thread output stream.
  4. Close Socket: Disconnect the client to connect to the server, release the line

Java Api:

  • The client program can create an object using the Socket class, created at the same time automatically initiates a connection to the server side. Socket constructor is:
Socket(String host,int port)throws UnknownHostException,IOException:向服务器(域名是host。端口号为port)发起TCP连接,若成功,则创建Socket对象,否则抛出异常。
Socket(InetAddress address,int port)throws IOException:根据InetAddress对象所表示的IP地址以及端口号port发起连接。
Socket s = new 
Socket(192.168.1.160,9999);
OutputStream out = s.getOutputStream();
out.write(" hello".getBytes());
s.close();
  • The client process to establish socketAtClient object is to issue a request to the server socket connection

2.1 server to establish a ServerSocket object

  • Work process server program consists of the following four basic steps:
  • Call ServerSocket (int port): Creates a server socket, bound to the specified port. Listens for client requests.
  • Call accept (): listens for connection requests, if the client requests a connection, the connection is accepted, returns a communication socket object.
  • Socket class calls the object the getOutputStream () and getInputStream (): Get the input stream and output stream, start to send and receive network data.
  • Close ServerSocket and Socket object: Client Access finished, close communication socket

Java Api:

ServerSocket ss = new ServerSocket(9999);
Socket s = ss.accept ();
InputStream in = s.getInputStream();
byte[] buf = new byte[1024];
int num = in.read(buf);
String str = new String(buf,0,num);
System.out.println(s.getInetAddress().toString()+:+str);
s.close();
ss.close();

2. UDP network programming

2.1 UDP communication network

  • DatagramSocket class and DatagramPacket implemented based on UDP protocol network program.
  • UDP datagram by datagram sockets DatagramSocket to send and receive, the system does not guarantee the UDP datagram will be able to secure sent to the destination, you can not determine when to arrive.
  • DatagramPacket objects encapsulate UDP datagram includes an IP address of the sending end and the receiving end of the port number and IP address and port number in the datagram.
  • Each UDP datagram protocol gives a complete address information, it is not necessary to establish a connection sender and recipient. As made express the same package.

2.2 API

  • Common method of DatagramSocket:
public DatagramSocket(int port)创建数据报套接字并将其绑定到本地主机上的指定端口。套接字将被
绑定到通配符地址,IP 地址由内核来选择。
public DatagramSocket(int port,InetAddress laddr)创建数据报套接字,将其绑定到指定的本地地址。本地端口必须在 065535 之间(包括两者)。如果 IP 地址为 0.0.0.0,套接字将被绑定到通配符地
址,IP 地址由内核选择。 
public void close()关闭此数据报套接字。 
public void send(DatagramPacket p)从此套接字发送数据报包。DatagramPacket 包含的信息指示:将要发送的数据、其长度、远程主机的 IP 地址和远程主机的端口号。 
public void receive(DatagramPacket p)从此套接字接收数据报包。当此方法返回时,DatagramPacket的缓冲区填充了接收的数据。数据报包也包含发送方的 IP 地址和发送方机器上的端口号。 此方法在接收到数据报前一直阻塞。数据报包对象的 length 字段包含所接收信息的长度。如果信息比包的长度长,该信息将被截短。 
public InetAddress getLocalAddress()获取套接字绑定的本地地址。 
public int getLocalPort()返回此套接字绑定的本地主机上的端口号。 
public InetAddress getInetAddress()返回此套接字连接的地址。如果套接字未连接,则返回 null。 
public int getPort()返回此套接字的端口。如果套接字未连接,则返回 -1
  • Common method of DatagramPacket:
public DatagramPacket(byte[] buf,int length)构造 DatagramPacket,用来接收长度为 length 的数据包。 length 参数必须小于等于 buf.length。 
public DatagramPacket(byte[] buf,int length,InetAddress address,int port)构造数据报包,用来将长度为 length 的包发送到指定主机上的指定端口号。length参数必须小于等于 buf.length。 
public InetAddress getAddress()返回某台机器的 IP 地址,此数据报将要发往该机器或者是从该机器接收到的。 
public int getPort()返回某台远程主机的端口号,此数据报将要发往该主机或者是从该主机接收到的。 
public byte[] getData()返回数据缓冲区。接收到的或将要发送的数据从缓冲区中的偏移量 offset 处开始,持续 length 长度。 
public int getLength()返回将要发送或接收到的数据的长度。

2.3 java Code

  • Process:
  1. DatagramSocket与DatagramPacket
  2. Establishing the transmitting side, the receiving end
  3. Set-up packet
  4. Call transmission, the receiving method Socket
  5. Close Socket
  • Transmission and the receiver are two separate program running
  • The sender
DatagramSocket ds = null;
try {
	ds = new DatagramSocket();
	byte[] by = "hello,atguigu.com".getBytes();
	DatagramPacket dp = new DatagramPacket(by, 0, by.length, 
	InetAddress.getByName("127.0.0.1"), 10000);
	ds.send(dp);
} catch (Exception e) {
	e.printStackTrace();
} finally {
	if (ds != null)
		ds.close();
}
  • The receiving end
    at the receiving end, to specify port is listening.
DatagramSocket ds = null;
try {
	ds = new DatagramSocket(10000);
	byte[] by = new byte[1024];
	DatagramPacket dp = new DatagramPacket(by, by.length);
	ds.receive(dp);
	String str = new String(dp.getData(), 0, dp.getLength());
	System.out.println(str + "--" + dp.getAddress());
} catch (Exception e) {
	e.printStackTrace();
} finally {
	if (ds != null)
		ds.close();
}

3. URL class

  • URL (Uniform Resource Locator): Uniform Resource Locator, which indicates the address of a resource on the Internet.
  • It is a specific URI, namely URL can be used to identify a resource, but also indicates how locate this resource.
  • By URL we can access various network resources on the Internet, such as the most common www, ftp sites. By parsing browser can find the appropriate files or other resources on the network of a given URL.
  • The basic structure consists of 5 parts of the URL: <Transfer Protocol>: // <host name>: <port number> / <filename> # piece name list of parameters?
    , For example:
    http://192.168.1.100:8080/path/ ? A index.jsp # username & password = xxx xxxx =
    # fragment name: the anchor, such as reading novels, positioning to the chapter
    parameter list format: parameter name = value & parameter parameter name = parameter value ...
  • java implementation class used java.net.URL identification URL, URL constructor:
public URL (String spec):通过一个表示URL地址的字符串可以构造一个URL对象。例
URL url = new URL ("http://www.xxxxxxx.com/"); 
public URL(URL context, String spec):通过基 URL 和相对 URL 构造一个 URL 对象。
URL downloadUrl = new URL(url, “download.html")
public URL(String protocol, String host, String file); 
new URL("http", "www.atguigu.com", “download. html");
public URL(String protocol, String host, int port, String file); 
URL gamelan = new URL("http", "www.atguigu.com", 80, “download.html");

After generating a URL object, its attributes can not be changed, there is a method to get the properties:

public String getProtocol( ) 获取该URL的协议名
public String getHost( ) 获取该URL的主机名
public String getPort( ) 获取该URL的端口号
public String getPath( ) 获取该URL的文件路径
public String getFile( ) 获取该URL的文件名
public String getQuery( ) 获取该URL的查询名

4. URLConnection class (for the HTTP protocol)

  • The method openStream URL (): read the data from the network
  • If you wish to output data, for example, the server-side CGI (Common Gateway Interface -Common Gateway Interface- for short, is the interface to the user's browser and server applications connected) program to send some data, you must first establish a connection with the URL, and then ability to read and write, this time need to use the URLConnection.
  • URLConnection: represents a connection to the remote object referenced by the URL. When establishing a connection with a URL, first the openConnection () generated by a method corresponding to URLConnection object on a URL object. If the connection procedure fails, the generated IOException.
URL netchinaren = new URL ("http://www.xxxxxxxx.com/index.shtml"); 
URLConnectonn u = netchinaren.openConnection( );
  • URLConnection object acquired through the input and output streams, which can interact with a conventional CGI programs.
public Object getContent( ) throws IOException
public int getContentLength( )
public String getContentType( )
public long getDate( )
public long getLastModified( )
public InputStream getInputStream( )throws IOException
public OutputSteram getOutputStream( )throws IOException

4.1 URI difference, URL and URN of

  • URI, is the uniform resource identifier, uniform resource identifier, used to uniquely identify a resource. The URL is a uniform resource locator, a Uniform Resource Locator, which is a specific URI, namely URL can be used to identify a resource, but also indicates how locate this resource.
    The URN, uniform resource name, uniform resource name, the resource is identified by name, such as mailto: [email protected]. In other words, URI is an abstract, high-level definition of the concept of uniform resource identifier, and the URL and URN are specific resources identified. URL and URN is a kind of URI.
  • In Java's URI in a URI instance it can represent absolute or relative, as long as it meets the URI syntax rules. The URL class is not only in semantics, also contains information to locate the resources, so it can not be a relative.

5. Summary

  • A computer located in a network has a unique IP address, so that different hosts can be distinguished from each other.
  • The client - server is one of the most common network application model. Server is a hardware or software to provide certain services to their clients. The client is a user application for accessing the service provided by a server. The port number is access to a place of service, which is used to distinguish between multiple services on the same physical machine. Each socket for connecting a communication session between the client and the server, the client and server use a different socket. TCP protocol for implementing a connection-oriented session.
  • Java functions concerning network are defined in the java.net package. Java represents the IP address InetAddress object that has two fields: the host name (String) and IP address (int).
  • Socket and ServerSocket class implements client-based TCP protocol - server program. Socket is a connection between the client and server connections created details are hidden. This connection provides a secure data transmission channel which is the TCP protocol can be solved because the data loss during transmission, damage, repeated, scrambled and network congestion problems, which ensures reliable data transfer.
  • URL and URLConnection class provides the most advanced network applications. Location of network resources to the same URL on the Internet represent a variety of network resources. You can create connections between applications and network resources represented by the current URL by URL object, so the program can read the current network resource data, or to transmit their data to the network up.
Published 336 original articles · won praise 77 · views 570 000 +

Guess you like

Origin blog.csdn.net/feicongcong/article/details/104906088