Author: yarshray
For a variety of purposes, you must write this article, simply because the nearest work and Java's socket is related. So, there is a written idea. Similarly, I don't want to write the article too complicated, so Light out your own experience. In fact, the network programming is simple to understand the two computers. For programmers, you can master a programming interface and use a programming model. It will seem simpler. Java SDK offers some relatively simple API to complete these work. Socket is one of them. For Java. These APIs exist in the package of java.net. So just import this package, you can prepare network programming. Network programming The basic model is the client to the server model. Simple saying is to communicate with each other between the two processes, then one of them must provide a fixed location, and the other needs to know this fixed location. And build between the two Contact .. Then complete the data of the data. It is often referred to as a server for a fixed location, and the establishment of a connection is often called the client. Based on this simple model, you can enter the network program. Java's model There are many kinds of APIs. Here I just want to introduce the programming interface for Socket. For Java, the Socket programming interface has been simplified. First let's discuss how the servers who provide fixed positions are created. Java provides ServerSocket To support it. In fact, when you create a powerful object of this class and provide a port resource you create a fixed location allowing other computers to access you. Serversocket Server = New Serversocket (6789); Here you should pay more It must be unique to the allocation of the port. Because the port is unique to uniquely identify each computer. In addition, the port number is between 0 ~ 65535, the first 1024 ports have been reserved as a retained port of TCP / IP, so you The allocated port can only be 1024. Well. We have a fixed position. Now it is a connection. The cable is first requested by the client. So Java also provides a socket object. Support it. As long as the client creates an instance object of a socket, it is possible to support. Socket client = new socket (inetaddress.getlocalhost (), 5678); The client must know the IP address of the server. For a little Java An instance of a related class inetaddress This object must be provided through its static method. Its static method mainly provides a method of obtaining the native IP and directly get inetaddress directly through the name or IP. Ok. The method above is basically To create a connection, the two computers communicate with each other. But how is the data transfers? In fact, I / O operation is always related to network programming. Because the underlying network is continuing data. Unless remote call, process problems The core is executed. Otherwise, the interaction of the data is still on I / O operation. So you must import java.io this package. Java's IO operation is not complicated. It provides readers for byte streams and Unicode And writer, and then also provide a buffering read / write. BufferedReader IN = New BufferedReader (server.getinputStream ()))); PrintWriter out = new PrintWriter (Server.getputstream ());
The above two sentences are to establish buffers and convert the original byte stream to Unicode. The original byte stream is derived from two methods of socket. GetInputStream () and getOutputStream (). It is used to get input and output, respectively. Then there is a basic model and basic operating tool. We can make a simple Socket routine. Service: import java.io. *; Import java.net. *;
public class MyServer {public static void main (String [] args) throws IOException {ServerSocket server = new ServerSocket (5678); Socket client = server.accept (); BufferedReader in = new BufferedReader (new InputStreamReader (client.getInputStream ()) ); Printwriter out = new printwriter (case); while (true) {string str = in.readline (); system.out.println (STR); Out.println ("Has Receive ...." ); Out.flush (); if (str.equals ("end")) Break;} client.close ();}} This program is the main purpose of this program is that the server is constantly receiving the information written by the client. Customer The machine will send the "END" string to exit the program. And the server will also make "Receive" respond. Inform the client that the message has been received.
Client code: import java.net. *; Import java.io. *;
public class Client {static Socket server; public static void main (String [] args) throws Exception {server = new Socket (InetAddress.getLocalHost (), 5678); BufferedReader in = new BufferedReader (new InputStreamReader (server.getInputStream ()) ); PrintWriter out = new PrintWriter (server.getOutputStream ()); BufferedReader wt = new BufferedReader (new InputStreamReader (System.in)); while (true) {String str = wt.readLine (); out.println (str) Out.flush (); if (str.equals ("end")) {breaf;} system.out.println (in.readline ());} server.close ();}}
The client code is accepting the customer keyboard input and outputs the information, and then outputs "end" to do exit identification.
This program is just a simple communication between two computers. If you have multiple customers accessed a server? You can try again to run a client, the result will throw an exception. So how many clients are implemented? ?
In fact, simple analysis, you can see that the main channels of customers and service communications are Socket itself. The server through the Accept method is consent to establish communication. This way when the customer builds Socket. Server will also use this The line is coming back. So, so as long as we exist multiple connectors. Then our program can become as follows:
server:
Import java.io. *; import java.net. *;
public class MyServer {public static void main (String [] args) throws IOException {ServerSocket server = new ServerSocket (5678); while (true) {Socket client = server.accept (); BufferedReader in = new BufferedReader (new InputStreamReader (client .GetinputStream ())); printwriter out = new printwriter (case); while (true) {string str = in.readline (); system.out.println (Str); out.println ("Has Receive .... "); out.flush (); if (str.equals (" end ")) Break;} client.close ();}}} This only added an outer WHILE loop. This loop The purpose is that when a customer comes in a socket until this customer completes the interaction of the server, it is also an "end" message that the customer is accepted. Then now achieve the interaction between multiples. But. But. The problem is coming again. Although I solved a multi-customer, it is queued to execute. That is to say, when a customer and server completes a communication, the next customer can come in and the server interaction. Can't do it at the same time. So how Can you achieve both communicating and simultaneous communication? Obviously this is a parallel execution problem. So thread is the best solution. Then the following question is how to use threads. The first thing to do is Create a thread and make it touch with the network connection. Then be implemented by the thread. To create a thread either directly inherited Thread Either to implement the runnable interface, to create and socket contacts As long as the reference is passed. Threads must rewrite the RUN method. The Run method does something. It is what you have just made of single-threaded version main. So our program turned this: import java.io. *; Import java.io. *;
public class MultiUser extends Thread {private Socket client; public MultiUser (Socket c) {this.client = c;} public void run () {try {BufferedReader in = new BufferedReader (new InputStreamReader (client.getInputStream ())); PrintWriter OUT = New PrintWriter (Client.getoutputStream ()); // Mutil User But Can't Parallel While (True) {String Str = In.readLine (); System.out.Println (Str); Out.println ("HAS Receive .... "); out.flush (); if (Str.Equals (" end ")) Break;} client.close ();} catch (ooException ex) {} finally {}} public static void main (String [] args) throws IOException {ServerSocket server = new ServerSocket (5678); while (true) {// transfer location change Single User or Multi User MultiUser mu = new MultiUser (server.accept ()); mu.start ( }}} My class has inherited from the Thread class. And through the constructor transfer reference and the customer socket. This way is there. A communication pipe. Similarly we can fill in the RUN method. The operation is handed over to the thread. Socket in parallel in parallel is built.
My article is over. Although my article is over here. But there is still a lot of operations related to Java's socket. Everyone will continue to work hard ...