Basic knowledge of the network:
In Java, the network program has two protocols: TCP and UDP,TCP are reliably connected by a handshake protocol, and UDP is not connected.
IP Address: The identity card used to mark a computer.
The IP address consists of the network address (the determined network) and the host address (the host in the network).
Subnet mask: In order to differentiate between network addresses and host addresses.
IP addresses are classified as Class A addresses, Class B addresses, Class C addresses (often used), Class D addresses, and e-addresses.
127.0.0.1 (localhost) is a native address.
IPV4 and IPV6
The IPV4 uses 4 decimal digits, which is 32-bit binary.
SMTP is a Simple Mail Transfer protocol and the port number is 25.
Telnet is used to connect to a remote computer or to a service provided by an Internet computer. Each service will have a port set.
Give a similar Telnet IP port to communicate with a specific service
If you want to connect to the Internet service, not only to give the port, but also to give the name of the computer, only the IP address and port number, you can request the service, and receive the answer.
URLs and URIs
URI: A Uniform Resource identifier that identifies a Web resource, including two parts.
(1) URL: Uniform Resource Locator. A URI that can pinpoint the data
(2) URN: Uniform Resource name. In addition to the URI of the URL
In Java, URIs and URLs are two separate classes, URI classes are dedicated to parsing, and URLs are used for communication.
URL1. URI classification
Absolute and relative:
(1) An absolute URI refers to a definite protocol. For example Http,ftp. Separated by/in the back
(2) There is no scheme for relative URIs.
Transparent and opaque:
(1) An opaque URI is a URI that cannot be parsed. An opaque URI is an absolute URI. The part behind scheme is not cut with/.
Layering and non-layering:
(1) The hierarchy is either an absolute transparent URI or a relative URI.
All of the pages are in port 80.
Role of 2.URI: (1) parsing
Format of URI:
[scheme:] Scheme-specific-part [#fragment]
Scheme means the protocol used, which can be http\https\ftp\file and so on.
Scheme-specific-part is the rest of the section.
Further subdivision:
[scheme:] [//Authority] [Path] [? Query] [#fragment]
Regular usage:
- Getscheme () obtain scheme;
- Getschemespecificpart ()
- GetPath ()
- Getauthority ()
(2) Conversion of relative identifiers and absolute identifiers
Resolve and relative functions.
Demo Sample code:
Task 1: Get the HTML code for a specific URL.
Task 2: Parse the address information.
Task 3: Absolute address and relative address translation
package org.core;import java.net.*;import java.util.*;p ublic class URLTest1 {public static void Main (string[] args) throws Exception {URL url = new URL ("http://www.ecnu.edu.cn"); Scanner in = new Scanner (Url.openstream ()), while (In.hasnextline ()) {String str = in.nextline (); System.out.println (str);} Uri uri = new Uri ("Http://blog.csdn.net/xiazdong"); System.out.println (Uri.getscheme ()); System.out.println (Uri.getschemespecificpart ()); System.out.println (Uri.getauthority ()); System.out.println (Uri.getuserinfo ()); System.out.println (Uri.gethost ()); System.out.println (Uri.getport ()); System.out.println (Uri.getpath ()); System.out.println (Uri.getquery ()); System.out.println (Uri.getfragment ()); String str = "/article/details/6705033"; URI combined = uri.resolve (str);//The path of the URI to make the str absolute address System.out.println (Combined.getscheme () + Combined.getschemespecificpart ()); URI relative = uri.relativize (new Uri (str)); System.out.println (Relative.getschemespecificpart ());}}
The role of URLs and Urlconnectionurl
1. Suppose you want to get the HTML source for a Web page, for example Http://blog.csdn.net/xiazdong only needs to:
(1) URL url = new URL ("Http://blog.csdn.net/xiazdong");
(2) Scanner in = new Scanner (url.openstream());
We can.
2. Get Message header information
- URLConnection connection = Url.openconnection ();
- Connection.getheaderfields () returns a map<string,list<string>>
- Connection.getcontentlength ();
- Connection.getcontenttype ();
- Connection.setdooutput (true) to get the output stream
- Connection.getoutputstream ();
- Connection.getinputstream ();
Sample Code Demo:
Package Org.core;import java.net.*;import sun.misc.*;import java.util.*;import java.io.*;p ublic class urlconnectiontest {public static void main (string[] args) throws Exception {String urlname = "Http://java.sun.com"; URL url = new URL (urlname); URLConnection connection = Url.openconnection (); map<string, list<string>> map = Connection.getheaderfields (); for (map.entry<string, List<String >> Entry:map.entrySet ()) {String key = Entry.getkey (); list<string> value = Entry.getvalue (); SYSTEM.OUT.PRINTLN (key + ":" + Value);}}}
In the Web page, suppose to submit data to webserver, usually send data to webserver, and then webserver delegate a script to process the data, return a corresponding.
There are usually two ways to send data: Get and post.
(1) The Get method is to directly follow the data behind the URL, to Name=value for transmission,
Each data is cut with &, the spaces in value are replaced with a +, non-alphanumeric is substituted with%, followed by two 16 binary numbers, which is called URL encoding . Urlencoder and Urldecoder
(2) The Post method is sent to the server via URLConnection, encoded in the same way as get. Urlencoder.encode (VALUE, "UTF-8");
Encoding and decoding are generally used when transferring Chinese.
Demo sample: Encode and decode via Urlencoder and Urldecoder
Slightly
InetAddress IP address or name based on domain name
There is no construction method, by:
(1) InetAddress I1 = inetaddress.getbyname (String) returns a inetaddress instance.
(2) If an address has more than one IP address, for example, Google, there are 3 IP addresses, call inetaddress[] I2 = Inetaddress.getallbyname (String);
Inetaddress.getlocalhost () Gets the inetaddress instance of this machine.
code example:
Package Org.core;import Java.net.inetaddress;public class Inetaddresstest {public static void main (string[] args) throws Exception{inetaddress local = Inetaddress.getlocalhost (); System.out.println ("Native Address:" +local.gethostaddress ()); System.out.println ("Native Name:" +local.gethostname ()); inetaddress[] remote = Inetaddress.getallbyname ("www.google.com") ; for (inetaddress a:remote) {System.out.println ("Address:" +a.gethostaddress ()); System.out.println ("Name:" +a.gethostname ());}}}
Socket (TCP)
A socket is a class used for communication between machines.
Socketclient:
(1) Socket s = new socket (ip,port); Open a socket, send request
(2) InputStream istream = S.getinputstream (); Receive data
(3) OutputStream ostream = S.getoutputstream (); Send data
Need to use PrintWriter and scanner packaging, and pay attention to PrintWriter's own active buffer.
Socketserver: Note that multiple clients visit the server at the same time: multithreading
(1) ServerSocket Server = new ServerSocket (port);
(2) Socket s = server.accept (); The function will only return if there is a client request and connection
(3) InputStream istream = S.getinputstream (); Receive data
(4) OutputStream ostream = S.getoutputstream (); Send data
Need to use PrintWriter and scanner packaging, and pay attention to PrintWriter's own active buffer.
We need to use the println () function when using PrintWriter;
When either the server or the client requests the end of the communication, it stops immediately.
Issue 1: Where a blockage occurs in the socket:
(1) When the socket is instantiated, it is blocked.
(2) in In.nextline () similar operation will be blocked.
Workaround:
(1) For the first problem, the workaround:
- Socket s = new socket (), no connection socket established
- S.connect (New Inetsocketaddress (Host,port), timeout), set timeout.
(2) For the second problem, the workaround is to set the S.setsotimeout (long) setting time-out
Issue 2: When the client wants to close the socket, but is not sure if the server is still sending the data, it will be disconnected just once it is closed.
Workaround:
Socket.shutdownoutput () close the output stream
Socket.shutdowninput () close the input stream
Half-closed Demo sample code: The client sends hello to the server, closes the output stream at the same time, closes the input stream when the server receives it, waits 5 seconds to send echo hello to the client.
Client:
Import java.net.*;import java.io.*;import java.util.*;p ublic class Shutdownoutputclient {public static void main (String [] args) throws Exception {socket s = new socket ("localhost", 8819); Scanner in = new Scanner (S.getinputstream ()); PrintWriter out = new PrintWriter (S.getoutputstream (), true); Out.println ("Hello");//output Hellos.shutdownoutput ();// Close the output stream System.out.println ("close Connection"), while (In.hasnextline ()) {System.out.println (In.nextline ());} S.close ();}}
Server:
Import java.net.*;import java.io.*;import java.util.*;p ublic class Shutdownoutputserver {public static void main (String [] args) throws Exception {ServerSocket server = new ServerSocket (8819); Socket s = server.accept (); Scanner in = new Scanner (S.getinputstream ()); PrintWriter out = new PrintWriter (S.getoutputstream (), true); String str = in.nextline (); System.out.println (str); S.shutdowninput (); SYSTEM.OUT.PRINTLN ("Close input stream"); Thread.Sleep (OUT.PRINTLN); ("Echo:" +str); S.close ();}}
Synthetic code Example : Implement a simple peer communication program, through multi-threading, a thread to receive data, a thread to send data.
User 1:
Import java.util.*;import java.io.*;import java.net.*;p ublic class client{public static void Main (String[]args) throws Exception{socket s = new Socket ("localhost", 8819); PrintWriter out = new PrintWriter (S.getoutputstream (), true); Thread t = new Thread (new Receive (s)); T.start ();//The following code is used to send data Scanner in = new Scanner (system.in);//keyboard input while ( In.hasnextline ()) {//continuously out.println (In.nextline ());//Send keyboard input data}}}class receive implements runnable//This class is used to receive data { Private socket S;public Receive (socket s) {THIS.S = s;} public void Run () {Try{scanner in = new Scanner (S.getinputstream ());//in: receiving data string str = Null;while (true) {str = In.nextli NE (); SYSTEM.OUT.PRINTLN ("server says:" +STR);//print receive Data}}catch (Exception e) {}}}
User 2:
Import java.util.*;import java.io.*;import java.net.*;p ublic class server{public static void Main (String[]args) throws Exception{serversocket Server = new ServerSocket (8819); Socket s = server.accept (); PrintWriter out = new PrintWriter (S.getoutputstream (), true); Thread t = new Thread (new Receive1 (s));//T.start ();//The following code is used to send data Scanner in = new Scanner (system.in);//keyboard input while ( In.hasnextline ()) {//continuously out.println (In.nextline ());//Send keyboard input data}}}class RECEIVE1 implements runnable//This class is used to receive data { Private socket S;public Receive1 (socket s) {THIS.S = s;} public void Run () {Try{scanner in = new Scanner (S.getinputstream ());//in: receiving data string str = Null;while (true) {str = In.nextli NE (); SYSTEM.OUT.PRINTLN ("client says:" +STR);//print receive Data}}catch (Exception e) {}}}
The above program belongs to C/S and needs to maintain the client and server code at the same time.
b/S: Browser and server, only need to maintain one side of the code.
The chat tool uses UDP a lot, because we usually also encounter a message that we send to another person, and one person has not received the situation.
Datagrampacket and Datagramsocket Datagrams
code example : Implement server to send data to the client.
Client:
Package Org.core;import Java.net.*;import java.io.*;p ublic class Datagramclient {public static void main (string[] args) t Hrows exception{byte[]buf = new byte[1024];D atagrampacket packet = new Datagrampacket (buf,1024);D Atagramsocket client = n EW Datagramsocket (9000); client.receive (packet); String str = new String (Buf,0,packet.getlength ()); System.out.println (Packet.getaddress (). GetHostName () + ":" +str); Client.close ();}}
Server:
Package Org.core;import Java.net.datagrampacket;import Java.net.datagramsocket;import java.net.InetAddress;public Class Datagramserver {public static void main (string[] args) throws Exception {Datagramsocket Server = new Datagramsocket (3 000); String str = "Hello World";D atagrampacket packet = new Datagrampacket (Str.getbytes (), Str.length (), Inetaddress.getlocalhost (), 9000); Server.send (packet); Server.close ();}}
QQ chat App
Server Side
Package Org.xiazdong.server;import Java.awt.borderlayout;import Java.awt.event.actionevent;import Java.awt.event.actionlistener;import Java.io.bufferedreader;import Java.io.inputstreamreader;import Java.io.printstream;import Java.net.inetaddress;import Java.net.serversocket;import Java.net.Socket;import Javax.swing.jbutton;import Javax.swing.jframe;import Javax.swing.jpanel;import Javax.swing.JScrollPane;import Javax.swing.jtextarea;import Javax.swing.jtextfield;public class Server3 extends jframe{static JTextArea area; JTextField field; JButton button;static printstream writer;public Server3 () {this.settitle ("server"); This.setsize (400,500); area = new JTextArea (25,30); area.seteditable (false); field = new JTextField; button = new JButton ("commit"); JPanel panel = new JPanel (); JScrollPane sp = new JScrollPane (area), This.add (sp,borderlayout.center);p anel.add (field);p Anel.add (button); This.add (Panel,borderlayout.south); this.setvisible (true); This.setdefaultcloseoperation (JFrame.EXIT_ON_CLOSE); button.addActionListener (new ActionListener () {@Overridepublic void actionperformed (ActionEvent e) {String text = Field.gettext (); writer.println (text); Area.append ("I:" +text+ "\ n"); Field.settext ("");}});} public static void Main (string[] args) throws Exception {Server3 s = new Server3 (); ServerSocket Server = new ServerSocket (8899); SYSTEM.OUT.PRINTLN ("Start monitoring ..."); Socket socket = server.accept (); InetAddress address = socket.getinetaddress (); String name = Address.getlocalhost (). GetHostName (); System.out.println (name+ "Connected"); BufferedReader reader = new BufferedReader (New InputStreamReader (Socket.getinputstream ())); writer = new PrintStream ( Socket.getoutputstream (), true), while (true) {String = Null;line = Reader.readline (), and if (line! = null) {Area.append (" Client: "+line+" \ n ");}}}
Client Side
Package Org.xiazdong.client;import Java.awt.borderlayout;import Java.awt.event.actionevent;import Java.awt.event.actionlistener;import Java.io.bufferedreader;import Java.io.inputstreamreader;import Java.io.outputstream;import Java.io.printstream;import Java.io.printwriter;import Java.net.Socket;import Javax.swing.jbutton;import Javax.swing.jframe;import Javax.swing.jpanel;import Javax.swing.JScrollPane;import Javax.swing.jtextarea;import Javax.swing.jtextfield;public class Client3 extends jframe{static JTextArea area; JTextField field; JButton button;static printwriter writer;public Client3 () {This.settitle ("client"); This.setsize (400,500); area = new JTextArea (25,30); area.seteditable (false); field = new JTextField; button = new JButton ("commit"); JScrollPane sp = new JScrollPane (area); JPanel panel = new JPanel (), This.add (sp,borderlayout.center);p anel.add (field);p Anel.add (Button), This.add (panel, Borderlayout.south); this.setvisible (true); This.setdefaultcloseoperation (jframe.exit_on_close); button.adDactionlistener (new ActionListener () {@Overridepublic void actionperformed (ActionEvent e) {String text = Field.gettext ( ); writer.println (text); Area.append ("I:" +text+ "\ n"); Field.settext ("");}}); public static void Main (string[] args) throws Exception{client3 C = new Client3 (); Socket socket = new Socket ("127.0.0.1", 8899); OutputStream out = Socket.getoutputstream (); BufferedReader reader1 = new BufferedReader (New InputStreamReader (Socket.getinputstream ())); writer = new PrintWriter ( Out,true); System.out.println ("Successfully connected with server ..."); while (true) {String line = Reader1.readline (); Area.append ("Server:" +line+ "\ n ");}}}
PrintWriter's AutoFlush
Suppose printwriter writer = new PrintWriter (out,true);
The println (), printf (), format () functions are automatically refreshed when they are called, and no other functions, such as the Write () or print () functions, do not refresh themselves voluntarily.
Common Network Programming exceptions
The 1th exception is java.net.BindException:Address already in Use:jvm_bind. This exception occurs when the server side is doing a new ServerSocket (port) operation with a 0,65536 integer value. The exception is due to the fact that a port is already being started and is listening. At this time with the Netstat–an command, you can see a listending state of the port. Just need to find a port that is not occupied to solve the problem.
the 2nd exception is Java.net.ConnectException:Connection Refused:connect. This exception occurs when the client makes a new Socket (IP, Port) operation because the exception occurs because either the machine with the IP address cannot be found (that is, the current machine does not exist to the specified IP route), or the IP exists, but the specified port is not found for listening. This problem occurs, first check the client's IP and port is wrong, assuming that the correct clientping from the server to see if it can ping, assuming that ping (service server to ping off the need for another method), It will certainly solve the problem if the program on the server side listens to the specified port.
The 3rd exception is the Java.net.SocketException:Socket is closed, which can occur in both client and server. The reason for the exception is that you have actively closed the connection (called the Close method of the socket) and read and write the network connection.
The 4th exception is java.net.SocketException: (Connection reset or connect reset by Peer:socket write error). This exception can occur on both the client and server side, causing the exception to be two, the first of which is to assume that one end of the socket is closed (or shut down voluntarily or due to an abnormal exit), and that one end still sends the data, and the first packet that is sent throws the exception (Connect Reset by Peer). There is one end exit, but the connection is not closed when exiting, and the other end assumes that the exception is thrown when the data is read from the connection (Connection reset). The simple thing is that the read and write operations are caused by the disconnection of the connection.
The 5th exception is the Java.net.SocketException:Broken pipe. This exception can occur in both client and server. In the first case of the 4th exception (that is, after throwing socketexcepton:connect reset by Peer:socket write error), the exception is thrown if the data is further written. The solution to the first two exceptions is to first make sure that all network connections are closed before the program exits, followed by a check of the other's closed connection operation, and that the other person closes the connection after closing the connection.
Java Network programming