Java Network Programming, java Network Programming pdf

Source: Internet
Author: User

Java Network Programming, java Network Programming pdf

.TCP Program Design

In JAVA, Socket (Socket) is used to develop TCP programs. Using this type can easily establish reliable, bidirectional, continuous, and point-to-point communication connections.

In Socket program development, the server uses ServerSocke to wait for the client connection. For java Network programs, each client uses a Socket object.

.Common ServerSocket class methods:

Serial number Method Type Description
1 Public ServerSocket (int port) throws IOException Constructor Create a ServerSocket instance and listen to the specified port.
2 Public Socket accept () throws IOException Common functions Wait for client connection. This method has been blocked before connection
3 Public InetAddress getInetAddress () Common functions Returns the IP address of the server.
4 Public boolean isClosed () Common functions Returns the shutdown status of ServerSocket.
5 Public void close () throws IOException Common functions Disable ServerSocket

When the server is running, the accept () method is used to wait for the client to connect. After this method is executed, the server enters the blocking state and the program can continue to run until the client connects. The Return Value Type of this method is Socket, and each Socket represents a client object.

Common Methods for. Socket classes:

Serial number Method Type Description
1 Public Socket (String host, int port) throws UnknownHostException, IOException Structure Construct a Socket object and specify the host name and port number of the server to be connected.
2 Public InputStream getInputStream () throws IOException Normal Returns the input stream of this socket.
3 Public OutputStream getOutputStream () throws IOException   Returns the output stream of this socket.
4 Public void close () throws IOException   Disable this Socket
5 Public boolean isClosed ()   Determine whether the socket is closed

. The first TCP program -- Echo program

Echo program is a typical case of network programming communication interaction. It is called a Response Program, that is, what content the client inputs. The server will add "ECHO: and send the information back to the client.

The previous program code, the server will exit after each execution, because the server can only accept connections from one client, mainly because the accept () method can only be used once, in this program

The circular method uses the accept () method. After each client completes execution, the server can wait for the user to connect again.

Single-thread example:

EchoClient 
 1 public class EchoClient { 2     public static void main(String[] args) throws IOException { 3  4         Socket client = new Socket("localhost", 8888); 5         BufferedReader buf = null; 6         PrintStream out = null; 7         out = new PrintStream(client.getOutputStream()); 8         out.println(1); 9         BufferedReader input = null;10         input = new BufferedReader(new InputStreamReader(System.in));11         buf = new BufferedReader(new InputStreamReader(client.getInputStream()));12         boolean flag = true;13 14         while (flag) {15             System.out.println("Please Key In:");16             String str = input.readLine();17             out.println(str);18             if ("bye".equals(str)) {19                 flag = false;20             } else {21                 String echo = buf.readLine();22 23                 System.out.println("1111" + echo);24             }25         }26         client.close();27         buf.close();28     }29 }

Single-thread example:

EchoServer 
1 public class EchoServer {2 public static void main (String [] args) throws IOException {3 ServerSocket server = null; 4 Socket client = null; 5 PrintStream out = null; 6 BufferedReader buf = null; 7 server = new ServerSocket (8888); 8 boolean f = true; 9 while (f) {10 System. out. println ("Server Running, Waiting for Client"); 11 client = server. accept (); 12 out = new PrintStream (client. getOutputStream (); 13 // get the information entered by the client 14 buf = new BufferedReader (new InputStreamReader (15 client. getInputStream (); 16 // instantiated output end 17 out = new PrintStream (client. getOutputStream (); 18 boolean flag = true; 19 while (flag) {20 String str = buf. readLine (); 21 if (str = null | "". equals (str) {22 flag = false; 23} else {24 if ("bye ". equals (str) {25 flag = false; 26} else {27 out. println ("ECHO" + str); 28} 29} 30} 31 out. close (); 32 client. close (); 33} 34 server. close (); 35} 36 37}

Multithreading example:

EchoThread 
 1 public class EchoThread implements Runnable { 2  3     private Socket client = null; 4  5     public EchoThread(Socket client) { 6         this.client = client; 7     } 8  9     public void run() {10         PrintStream out = null;11         BufferedReader buf = null;12 13         try {14             buf = new BufferedReader(new InputStreamReader(15                     client.getInputStream()));16             out = new PrintStream(client.getOutputStream());17             boolean flag = true;18 19             while (flag) {20                 String str = buf.readLine();21                 if (str == null || "".equals(str)) {22                     flag = false;23                 } else {24                     if ("bye".equals(str)) {25                         flag = false;26                     } else {27                         out.println("ECHO:" + str);28                     }29                 }30             }31             out.close();32             client.close();33         } catch (Exception e) {34         }35     }36 37 }

Multithreading example:

EchoServer 
 1 public class EchoServer { 2     public static void main(String[] args) throws IOException { 3         ServerSocket server = null; 4         Socket client = null; 5         PrintStream out = null; 6         BufferedReader buf = null; 7         server = new ServerSocket(8888); 8         boolean f = true; 9         while (f) {10             System.out.println("Server Running,Waiting for Client");11             client = server.accept();12             new Thread(new EchoThread(client)).start();13             14         }15         server.close();16     }17 18 }

On the server side, each client Socket connected to the server runs in the form of a thread, so that no matter how many client connections are there, the operation can be completed at the same time.

Not complete...

 

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.