Java Network Programming Adventure

Source: Internet
Author: User
Tags fully qualified domain name

Let's take a look at the main functions of the computer network: resource sharing; information transmission and centralized processing; load balancing and distribution processing; Integrated information services.


In fact, Java Network programming is the server through the ServerSocket to establish the monitoring, the client through the socket connected to the specified server, the communication between the two sides can communicate through the IO stream.



1. Understanding Network Programming


The Convention of Communication in the computer network is called the Communication protocol, and the communication protocol is responsible for setting up the processing standard of transmission rate, transmission code, code structure, Transmission Control step, error control and so on.

The OSI model for computer networks (reference standards for various computer networks) is as follows:


1) Upper layer protocol

Http,ftp,https

2) underlying protocol

Tcp / ip

IP (Internet Protocol, Internet Protocol ): A datagram protocol that supports inter-network interconnection.

TCP (Transmission Control Protocol, Transmission Control Protocol ): Higher security, generally no data loss.

UDP: More efficient, less secure, and potentially data loss.

Expansion: HTTP header: Just a piece of content that comes with the TCP protocol.

Communication Protocol Composition: Semantic part, grammar department rules for the Division and transformation.

Summary: The so-called protocol is to encapsulate their own text content on the basis of data transmission.


3) TCP/IP implementation in Java--socket
Socket implementation of TCP/IP,TCP/IP is just a document, each different language according to their own needs of the protocol for different parsing, and in Java, the implementation of TCP/IP is the socket.


4) IP address and port number

IP Address:32-bit integer (4 8-bit binary), Nic Unified responsible for global IP address planning, management, and Intel NIC, APNIC, ripe three network information centers specifically responsible for the United States and other regions of the IP address distribution, APNIC (headquartered at the University of Tokyo, Japan) is responsible for IP management in the Asia-Pacific region, and our IP address is also APNIC.

IP address is divided into a, B, C, D, E five categories:

Class A: 10.0.0.0-10.255.255.255

Class B: 172.16.0.0-172.31.255.255

Class C: 192.168.0.0-192.168.255.255


Port number:16-bit integer, 0-65535

Recognized Port: 0-1023

Registered Port: 1024-49151

Dynamic and private ports: 49152-65535



2.Java of network support


Classes such as the java.net package URL and URLConnection provide programmatic access to Web services, Urldecoder and Urlencoder provide ordinary strings and application/ X-www-form-urlencoded A static method that converts MIME strings to each other.


1) inetaddress

Java provides a inetaddress class that represents an IP address

public class Inetaddresstest {public static void main (string[] args) throws Exception {inetaddress IP = Inetaddress.getbyn Ame ("www.baidu.com"); According to the host name to obtain the corresponding InetAddress instance System.out.println ("Baidu can reach:" + ip.isreachable (2000)); Determine if it can reach System.out.println (ip.gethostaddress ()); Gets the IP string of the inetaddress instance inetaddress local = inetaddress.getbyaddress (new byte[]{127,0,0,1}); According to the original IP address to obtain the corresponding InetAddress instance System.out.println ("This machine can reach:" + local.isreachable (5000)); System.out.println (Local.getcanonicalhostname ()); Gets the fully qualified domain name of the InetAddress instance}}


2)Urldecoder and Urlencoder

Used for mutual conversions between ordinary strings and application/x-www-form-urlencoded MIME strings

public class Urldecodertest {public static void main (string[] args) throws Exception {//Will Application/x-www-form-urlencod The ED string is converted to a normal string keyWord = Urldecoder.decode ("Csdn%e5%8d%9a%e5%ae%a2", "utf-8"); System.out.println (KeyWord);//Convert ordinary string to application/x-www-form-urlencoded string urlstr = Urlencoder.encode (" CSDN blog "," Utf-8 "); System.out.println (URLSTR);} /** * Run Result: * CSDN Blog * CSDN%B2%A9%BF%CD */}


3) URLs, URLConnection, and Urlpermission

URL: A Uniform Resource locator that contains an input stream that can be opened to reach the resource.

A URI is also provided in Java: A Uniform Resource identifier, which cannot be used to locate any resource, can only be parsed, and the URL is a special case of a URI.

URLConnection: Communication connection between an application and a URL

HTTP connection between Httpurlconnection:url and URL

A program can send a request to a URL through an URLConnection instance and read the resource referenced by the URL.

If you want to use the input stream to read the contents of the URLConnection response and use the output stream to send request parameters, be sure to use the output stream before using the input stream.

URL url = new URL (path); Path: Defines the path to the download resource HttpURLConnection conn = (httpurlconnection) url.openconnection (); conn.setconnecttimeout (5000); Set timeout time Conn.setrequestmethod ("GET"); Set the Request method//Set the header information of the communication, set the access mode etc. conn.setrequestproperty ("Accept-language", "ZH-CN"); Conn.setrequestproperty ("Charset "," UTF-8 "); Conn.connect (); Establish an actual connection

The following procedure demonstrates sending a GET request, a POST request, and a response from a Web site to a Web site:

public class Getposttest {/** * Test send GET request and POST request * @param args */public static void Main (String args[]) {//Send GET request String s = Getposttest.sendget ("http://localhost:8888/GetPostServer/test.jsp", null); System.out.println (s);//Send POST request string S1 = Getposttest.sendpost ("http://localhost:8888/GetPostServer/login.jsp", "Name=zhangsan&pass=123"); System.out.println (s1);} /** * Request to send a GET method to a specified URL * @param URL to send the requested URL * @param param request parameter, format satisfies name1=value1&name2=value2 form * @return URL represents a remote resource The response */public static string sendget (string url, string param) {string result = ""; String urlname = URL + "?" + param;try {URL realurl = new URL (urlname); URLConnection conn = Realurl.openconnection (); Open and URL connection between//settings common Request Properties Conn.setrequestproperty ("Accept", "*/*"); Conn.setrequestproperty ("Connection", " Keep-alive "); Conn.setrequestproperty (" User-agent "," mozilla/4.0 "(compatible; MSIE 6.0; Windows NT 5.1; SV1); Conn.connect (); Establish the actual connection map<string, list<string>> map = Conn.getheaderfields (); Get all response header fields//Traverse all response header fields for (String Key:map.keySet ()) {System.out.println (key + "=" + map.get (key));} Try (//define BufferedReader input stream to read the response of the URL BufferedReader in = new BufferedReader (New InputStreamReader (Conn.getinputstream ( ) {String Line;while (line = In.readline ()) = null) {result + = "\ n" + Line;}}} catch (Exception e) {System.out.println ("Send GET request exception!") "+ e); E.printstacktrace ();} return result;} /** * Request to send a POST method to the specified URL * @param URL to send the request * @param param request parameter, format should meet the form of name1=value1&name2=value2 * @return URL represents far The response of the process resource */public static string sendpost (string url, string param) {string result = ""; try {url realurl = new URL (URL); URLConnection conn = Realurl.openconnection (); Open and URL connection between//settings common Request Properties Conn.setrequestproperty ("Accept", "*/*"); Conn.setrequestproperty ("Connection", " Keep-alive "); Conn.setrequestproperty (" User-agent "," mozilla/4.0 "(compatible; MSIE 6.0; Windows NT 5.1; SV1), or the Send POST request must be set to the following two lines conn.setdooutput (true); Conn.setdoinput (true); try (//Get the URLConnection object corresponding to theOutput stream PrintWriter out = new PrintWriter (Conn.getoutputstream ())) {//Send request parameter out.print (param);//Flush output stream buffer Out.flush ();} Try (//define BufferedReader input stream to read the response of the URL BufferedReader in = new BufferedReader (New InputStreamReader (Conn.getinputstream ( ) {String Line;while (line = In.readline ()) = null) {result + = "\ n" + Line;}}} catch (Exception e) {System.out.println ("send POST request exception! "+ e); E.printstacktrace ();} return result;}}
The Web site is as follows:
TEST.JSP:

<%@ page contenttype= "text/html; Charset=utf-8 "language=" java "errorpage=" "%><! Doctype>
LOGIN.JSP:

<%@ page contenttype= "text/html; Charset=utf-8 "language=" java "errorpage=" "%><%request.setcharacterencoding (" UTF-8 "); String name = Request.getparameter ("name"); String pass = request.getparameter ("Pass"), if (Name.equals ("Zhangsan") && pass.equals ("123")) {out.println (" Login Successful! ");} else {out.println ("Login failed! ");} %>



3. Network programming based on TCP protocol


TCP/IP protocol is a reliable protocol, it establishes a socket on both ends of the communication, thus forming a network virtual link between the communication ends to communicate, Java uses the socket object to represent the communication interface on both ends, and the socket generates IO stream for network communication.


1) using ServerSocket to create a TCP server

Create a ServerSocket to listen for connection requests from the client socket serversocket socket = new ServerSocket (10000); The port number is recommended to use more than 1024//using loops to accept requests from the client while (TRUE) {socket s = socket.accept ();//The socket can be used to communicate ...}
Note: There are two sockets per TCP connection and should be used when ServerSocket is finishedThe close () method of the ServerSocket closes the serversocket.

2) using the socket for communication

The client can use the socket's construction method to connect to the specified server

The socket provides the following two ways to get the input stream and output stream:

InputStream getInputStream (): Returns the input stream corresponding to the socket object

OutputStream getOutputStream (): returns the output stream corresponding to the socket object

Socket other common methods:

Set Timeout length: setsotimeout (int timeout)

Specifying the length of time for the socket connection server does not provide parameters for the specified length of time in the socket construction method, so you need to use the following code:

Create a non-connected socketsocket socket = new socket ();//allow the socket to connect to the remote server, if it is not connected after 10 seconds, the connection timeout is considered socket.connect (new inetaddress (host, Port), 10000);

The following is an example of network communication based on TCP protocol with the simplest network communication.

Server-side:

public class Server {public static void main (string[] args) throws IOException {serversocket socket = new ServerSocket (100 ) while (true) {Socket s = socket.accept (); PrintStream PS = new PrintStream (S.getoutputstream ()); Wrap the socket corresponding to the output stream as Printstreamps.println ("You received the message from the server!"). "); For normal IO operation Ps.close (); S.close ();}}}

Client:

public class Client {public static void main (string[] args) throws IOException {socket socket = new Socket ("127.0.0.1", 1 0000); BufferedReader br = new BufferedReader (New InputStreamReader (Socket.getinputstream ())); String line = Br.readline (); For normal IO operation System.out.println ("Data from server:" + line); Br.close (); Socket.close ();}}


4. network programming based on UDP protocol


1) Send and receive data using Datagramsocket

UDP (user Datagram Protocol, Subscriber Datagram Protocol): Unreliable network protocol for non-connected, high communication efficiency.

UDP establishes a socket on both sides of the communication, but there is no virtual link between the two sockets, and these two sockets are just the objects that send and receive data.

Java provides Datagramsocket(itself a dock, does not maintain state, cannot generate IO stream, the only function is to accept and send datagrams) as a UDP-based socket, using datagrampacket represents a datagram sent and received by Datagramsocket.

The data sent and received by Datagramsocket is done through the Datagrampacket object.

The UDP and TCP comparisons are as follows:

TCP: Reliable, unlimited transmission size, need to establish a connection, error control overhead.

UDP: Unreliable, the transmission size limit is below 64KB, do not need to establish a connection, error control overhead is small.

Accept data:

Datagramsocket socket = new Datagramsocket (port); Port: Port number Datagrampacket packet = new Datagrampacket (buf, length); socket.receive (packet); Receive datagrams from Datagrampacket

Send data:

Datagramsocket socket = new Datagramsocket (port); Port: Port number Datagrampacket packet = new Datagrampacket (buf, length, address, port); socket.send (packet); Sending datagrams outward with a Datagrampacket object


2) Multi-point broadcast using MulticastSocket

Datagramsocket only allows datagrams to be sent to the specified destination address, and MulticastSocket can broadcast datagrams to multiple clients.

MulticastSocket inherits from Datagramsocket

Multipoint broadcasts are as follows:


You also need to add to the specified multicast address after you create the MulticastSocket object,multicastsocket use Joingroup (inetaddress multicastaddr) Method is added to the specified group, and the Leavegroup (inetaddress multicastaddr) method is used to detach from a group.

MulticastSocket the method used to send and receive datagrams is exactly the same as the datagramsocket. But MulticastSocket has a settimetolive (int ttl) method, and the TTL parameter is used to set the maximum number of networks the datagram can span (0: Stay on the local host; 1: local area network; 32: Can only be sent to the network on this site ; 64: Reserved in the region; 128: reserved on the continent; 255: all places), default 1.



5. Proxy Server

Starting from Java5, the java.net package provides a proxy (representing the broker server), Proxyselector (representing the proxy selector) two classes



Java Network Programming Adventure

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.