Jadam
Java Advanced Chapter (ii)--network communication
Network programming is a core part of every developer's tool, and after learning a lot of Java knowledge, we will step into a few big directions, and Java Network programming is one of them.
Today, the emphasis on networking is no more than that of a web-related program. In addition to classic applications such as e-mail, Web browsers, and remote logins, most major applications have some level of endoplasmic network functionality. For example, we use the IDE (ECLIPSE/IDEA) to communicate with the source code repository (github, etc.), such as word, you can open the file from the URL, or we play a number of online games, players in real-time against each other and so on. Java was the first programming language to be designed for Web applications from the outset, and one of the first two practical Java applications was a Web browser, and as the Internet continued to evolve, Java became the only language to build the next generation of Web applications. (Excerpt from Java NetWork programming--elliotte Rusty Harold )
First, Client/server
To enable communication between two computers, you must connect two computers with one network line. A server is a computer or program that provides information, a client is a computer or program that requests information, and a network is used to connect a server to a client to communicate with each other.
Let's look at a simple communication example.
The following server program is a server-side application that uses a Socket to listen on a specified port.
1 import java.io.IOException; 2 import java.io.InputStreamReader; 3 import java.io.reader; 4 import java.net.serversocket; 5 import java.net.socket; 6 7 public class server { 8 9 public static void main (String[] args) throws ioexception {10 int port = 9999;11 12 SYSTEM.OUT.PRINTLN ("-----------client start-----------"); 13 14 ServerSocket server = new ServerSocket (port);15 socket socket = Server.accept (); 16 &nbSp; reader reader = new inputstreamreader (Socket.getinputstream ());17 char chars[] = new char[1024];18 int len;19 stringbuilder builder = new stringbuilder ();20 while ((Len=reader.read (chars)) != -1) {21 builder.append (new string (Chars, 0, len)); 22 }23  SYSTEM.OUT.PRINTLN ("Receive information from the client: " + builder);24 reader.close (); 25 socket.close ();26 &Nbsp; server.close (); 27 }28 29 }
The following client is a clients program that connects to the server via the socket and sends a request, and then waits for a response.
1 import java.io.IOException; 2 import java.io.OutputStreamWriter; 3 Import java.io.writer; 4 import java.net.socket; 5 import java.util.scanner ; 6 7 public class client { 8 9 public static void main (String[] args) throws IOException {10 String host = "127.0.0.1";11 int port = 9999;12 13 system.out.println ("----------- Server start-----------");14 15 socket client = new socket (Host, port);16   Writer writer = new outputstreamwriter (Client.getoutputstream ());17 scanner in = new scanner (System.in);18 writer.write (In.nextline ());19 writer.flush (); 20 writer.close (); 21 client.close ();22 in.close (); 23 }24 25 }
Start the server first and run the following results:
Run the client again and enter the information you want to send, as follows:
At this point, the server receives the message sent by the client, as follows:
This is a simple socket communication, the specific analysis is shown below TCP.
Second, TCP
TCP Network program design refers to the use of the socket class to write a communication program, the specific examples refer to the above example.
Sockets use TCP to provide a mechanism for communication between two computers. The client program creates a socket and tries to connect to the server's socket. When the connection is established, the server creates a Socket object. The client and server can now communicate by writing and reading to the Socket object. The Java.net.Socket class represents a socket, and the Java.net.ServerSocket class provides a mechanism for the server program to listen to the client and establish a connection with them.
The steps to establish a TCP connection between two computers using sockets are as follows:
The server instantiates a ServerSocket object that communicates through the port on the server.
The server calls the Accept () method of the ServerSocket class, and the method waits until the client connects to the given port on the server.
When the server is waiting, a client instantiates a Socket object, specifying the server name and port number to request a connection.
The constructor of the Socket class attempts to connect the client to the specified server and port number. If the communication is established, a Socket object is created on the client to communicate with the server.
On the server side, the Accept () method returns a new socket reference to the server that is connected to the client's socket.
After the connection is established, each socket has an output stream and an input stream by using the I/O stream, and the client's output is streamed to the server-side input stream, and the client's input is streamed to the server-side output stream.
1. InetAddress
The InetAddress class in the java.net package is a class associated with an IP address that can be used to obtain information such as IP address, host address, and so on.
inetaddress IP = inetaddress.getlocalhost (); String localname = Ip.gethostname (); Gets the local host name string localip = Ip.gethostaddress (); Get the IP address of the local host
2. ServerSocket
The Servetsocket class in the java.net package is used to represent a server socket, and its primary function is to wait for a "request" from the network, which can wait for a connected socket (such as 9999 in the above instance) through the specified port.
While a server socket can be connected to a socket at a time, if multiple clients make a connection request at the same time, the server socket will put the client that requested the connection into the queue and then take a socket from it and connect to the new socket on the server. If the number of requested connections is greater than the maximum number of holds, the extra connection request is rejected.
ServerSocket the specific method can refer to the API, here only the Accept () method for a description. Calling the Accept () method returns a socket object that is connected to the client socket object, and the server-side socket object uses the Getoutputstream () method to obtain the output stream object. Will point to the client socket object using the getInputStream () method to obtain the input stream object, and vice versa.
It should be noted that the accept () method blocks the continuation of the thread until the customer's call is accepted, and the following code will not execute if there is no customer call server.
Third, UDP
User Packet Protocol (UDP) is another form of network information transmission, UDP-based communication is different from TCP-based communication, and the information transmission of UDP is faster, but it does not provide reliable guarantee.
1. Datagrampacket
The Datagrampacket class in the java.net package is used to represent the packet, constructed as follows:
Datagrampacket (byte[] buf, int length) Datagrampacket (byte[] buf, int length, inetaddress address, int port)
In the preceding construction method, the first specifies the memory space and size of the packet, the second not only specifies the memory space and size of the packet, but also specifies the destination address and port of the packet.
2. Datagramsocket
The Datagramsocket class in the java.net package is used to represent the socket for sending and receiving packets, constructed as follows:
Datagramsocket () datagramsocket (int port) datagramsocket (int port, inetaddress addr)
In the preceding construction method, the first creates a packet socket and binds it to any available port on the local host , the second creates the packet socket and binds it to the specified port on the local host , creates a packet socket and binds it to the specified native address .
Iv. Example Test
The following is a complete example of the following topics:
Establish the service-side program, the server-side program receives requests from the client;
Download the program from the Internet, English 900 sentences, each sentence occupies one line;
The server reads the file and saves it to the collection or list;
Create a client program that uses the format "sentence: < number #>,< number #>" to occur data. For example: Send "sentense:1,2,3", the service side of the corresponding number of sentences sent to the client, and to render;
The client needs to save the sentences sent by the server, and if the corresponding sentences have been saved, they will not be saved;
The client needs to store the data fetched from the server to the file.
1. Program Structure
2. Server.java
The class is a client class.
1 import java.io.*; 2 import java.net.ServerSocket; 3 import Java.net.socket; 4 import java.util.arraylist; 5 import java.util.list; 6 7 /** 8 * 9 * @author adamjwh10 * 11 */12 public class server {13 14 public static List<String> sentence;15 private static string filename = "Src/com/adamjwh/jnp/ex6_2/english900.txt";16 17 public static void main (String[] args) throws ioexception {18 sentence=new ArrayList<> (19&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN); ("-------- ---server start-----------"); 20 21 Filereader filereader = new filereader (filename);22 bufferedreader br = new bufferedreader (FileReader);23 24 String inputline = null;25 while ((inputLine = br.readline ()) != null) {26 sentence.add (inputline); 27 }28 29 ServerSocket ss = new ServerSocket (9999); 30 while (True) {31 &nbsP; socket sk =ss.accept ();32 serverthread st = new serverthread (SK);33 st.start ();34 }35 36 }37 }
2. Client.java
The class is a server class.
import java.io.bufferedreader;import java.io.filewriter;import java.io.inputstream;import java.io.inputstreamreader;import java.io.printstream;import java.net.socket;import java.util.scanner;/** * * @author adamjwh * */public class Client { private static string filename = "Src/com/adamjwh/jnp/ex6_2/result.txt"; public static void main (String[] args) { try { socket sk = new socket ("127.0.0.1", 9999); SYSTEM.OUT.PRINTLN ("-----------client start-----------"); PrintStream ps = new printstream (Sk.getoutputstream ()); system.out.print ("Send:"); Scanner sn = new scanner (system.in); string str = sn.nextline (); ps.println (str); inputstream is = sk.getinputstream (); inputstreamreader isr = new inputstreamreader (IS); BufferedReader br = new BufferedReader (ISR); //Writing Files filewriter fw = new filewriter (filename, true); //Read File string result = new readfile (). ReadFile (filename); string s; while (s = Br.readline ()) != null) { &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("Server push:" + s); if (!result.contains (s)) { fw.write (s + "\ n"); } } sk.shutdowninput (); Ps.close (); sk.close (); fw.close (); } catch (exception e) { e.printstacktrace (); } }}
3. Serverthread
Information interactions are implemented through threads.
1 import java.io.*; 2 import java.net.socket; 3 4 /** 5 * 6 * @author adamjwh 7 * 8 */ 9 public class ServerThread extends Thread{10 socket sk;11 public serverthread (Socket sk) {12 this.sk= sk;13 }14 public void run () {15 bufferedreader br=null;16 try{17 br = new bufferedreader (New inputstreamreader (Sk.getinputstream ()));18 string line&nBsp;= br.readline ();19 SYSTEM.OUT.PRINTLN ("Client:" +line);20 string[] split = line.split (":");21 string[] split1 = split[split.length - 1].split (",");22 sk.shutdowninput ();23 24 OutputStream os = Sk.getoutputstream ();25 26 Printstream bw = new printstream (OS);27 28 //returns information to the client 29 for (int i=0;i<split1.length;i++) {30 bw.print (Server.sentence.get (Integer.parseint (split1[i))%server.sentence.size ()) + "\ n");31 }32 bw.flush ();33 br.close ();34 sk.close ();35 }36 catch (ioexception e) {37 e.printstacktrace ();38 }39 }40 }
4. Running Results
Run the server first
Run the client again and enter the information
The server received a request from the client
The server pushes the result of the request to the client, where the client obtains the 174th, No. 258, and 5th sentences of the request and outputs it to the file
Here the test file I tested to 162 (that is, the 15th line of the file), you can see the file is appended with two lines of new sentences (174 and 258), and the 5th sentence because it has appeared before (the file's 1th line), so there is no additional 5th sentence to complete the above topic.
Java Advanced Article--network communication