In fact, a simple understanding of network programming is that the two computers communicate with each other. for programmers, it is much easier to master a programming interface and use a programming model. java SDK provides some relatively simple APIs to complete these tasks. socket is one of them. for Java. these APIS exist in the java.net package. therefore, you only need to import this package to prepare network programming.
The basic network programming model is the client-to-server model. simply put, two processes communicate with each other, and one of them must provide a fixed location, while the other only needs to know the fixed location. and establish the connection between the two .. then you can complete the data communication. a fixed location is usually called a server, and a client is usually used to establish a connection. based on this simple model, you can access network programming.
JAVA supports many APIs for this model. here I just want to introduce the socket programming interface. java has simplified socket programming interfaces. first, we will discuss how the service provider that provides a fixed position is built. java provides serversocket for its support. in fact, when you create a powerful object of this class and provide a port resource, you have created a fixed location for other computers to access you. java code
- Serversocket Server = new serversocket (6789 );
ServerSocket server=new ServerSocket(6789);
Note that the port distribution must be unique, because the port is used to uniquely identify the unique service of each computer. In addition, the port number ranges from 0 ~ The first 65535 ports have been reserved by TCP/IP. Therefore, you can only allocate 1024 ports later than 1024. okay. we have a fixed position. now we need a connection line. this connection line is first requested by the customer. therefore, Java also provides a socket object to support it. you only need to create a socket Instance Object for support. java code
- Socket Client = new socket (inetaddress. getlocalhost (), 5678 );
Socket client=new Socket(InetAddress.getLocalHost(),5678);
The client must know the IP address of the server. at one point, Java also provides a related class inetaddress. the instance of this object must be provided through its static method. its static method mainly provides the method of obtaining the local IP address and directly obtaining the inetaddress through the name or IP address.
Okay. The above method can basically establish a line for the two computers to communicate with each other. But how is data transmitted? In fact, I/O operations are always closely related to network programming. because the underlying network continues data. unless called remotely, the core of troubleshooting is execution. otherwise, Data Interaction depends on Io operations. therefore, you must also import Java. io package. java Io operations are not complex. it provides readers and writers for byte streams and Unicode, and then provides a buffer for reading and writing data. java code
- Bufferedreader in =
- New bufferedreader (New inputstreamreader (server. getinputstream ()));
- Printwriter out = new printwriter (server. getoutputstream ());
BufferedReader in=new BufferedReader(new InputStreamReader(server.getInputStream())); PrintWriter out=new PrintWriter(server.getOutputStream());
The above two statements are used to create a buffer and convert the original byte stream to Unicode. the original byte stream comes from two methods of socket. getinputstream () and getoutputstream. used to obtain the input and output respectively. now we have basic models and basic operation tools. we can make a simple socket routine.
Service provider: Java code
- 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 (client. getoutputstream ());
- While (true ){
- String STR = in. Readline ();
- System. Out. println (STR );
- Out. println ("has receive ....");
- Out. Flush ();
- If (Str. Equals ("end "))
- Break;
- }
- Client. Close ();
- }
- }
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(client.getOutputStream()); while(true){ String str=in.readLine(); System.out.println(str); out.println("has receive...."); out.flush(); if(str.equals("end")) break; } client.close(); } }
The main purpose of this program is that the server continuously receives the information written by the client only. the client will exit the program after sending the "end" string. and the server will also respond to "receive. inform the client that the message has been received.
Client code: Java code
- Import java.net .*;
- Import java. Io .*;
- Public class client {
- Static socket server;
- Public static void main (string [] ARGs) throws exception {
- Servers = 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 ")){
- Break;
- }
- System. Out. println (in. Readline ());
- }
- Server. Close ();
- }
- }
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")){ break; } System.out.println(in.readLine()); } server.close(); } }
The client code is to accept the customer's keyboard input, output the information, and then output "end" for exit identification.
This program is just a simple communication between two computers. What if multiple customers access one server at the same time? You can try to run another client and the result will throw an exception. How can we implement multiple clients?
In fact, after a simple analysis, we can see that the main channel for communication between customers and services is socket itself. the server agrees to establish communication with the customer through the accept method. in this way, when the customer establishes a socket. the server will also use this link for communication. so long as we have multiple connections. then our program can be changed to the following:
Server:
Java code
- 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 (client. getoutputstream ());
- While (true ){
- String STR = in. Readline ();
- System. Out. println (STR );
- Out. println ("has receive ....");
- Out. Flush ();
- If (Str. Equals ("end "))
- Break;
- }
- Client. Close ();
- }
- }
- }
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(client.getOutputStream()); while(true){ String str=in.readLine(); System.out.println(str); out.println("has receive...."); out.flush(); if(str.equals("end")) break; } client.close(); } } }
Here, only an outer while loop is added. the purpose of this loop is to assign a socket to a customer when they come in until the customer completes an interaction with the server. Here, the customer's "end" message is received. now the interaction between multiple customers is realized. however. the problem comes again. although this solution solves multiple customers, it is executed in queue. that is to say, when a customer communicates with the server once, the next customer can come in and interact with the server. cannot achieve simultaneous service. so how can we achieve both communication and communication at the same time? Obviously this is a problem of parallel execution, so the thread is the best solution.
The following question is how to use the thread. the first thing to do is to create a thread and connect it to the network. then, the thread executes the operation. to create a thread, either directly inherit the thread or implement the runnable interface. to establish a connection with the socket, you only need to pass the reference. to execute the thread, you must override the run method. what the run method does. this is what the single-threaded version main did. so our program becomes like this: Java code
- Import java.net .*;
- 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 (ioexception 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 ();
- }
- }
- }
import java.net.*; 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(IOException 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 is inherited directly from the Thread class. the constructor transmits the reference and establishes a connection with the customer socket. in this way, each thread will have it. A communication pipeline. similarly, we can enter the run method. hand over the previous operations to the thread for completion. in this way, the concurrent socket of multiple customers is established.