-

   rss_rss_hh_new

 - e-mail

 

 -

 LiveInternet.ru:
: 17.03.2011
:
:
: 51

:


[ ] - ,

, 11 2017 . 12:15 +

Java . .


-, , .


.


: , Stream Thread, , Thread.


(Sockets): , - , . (ServerSocket) (Socket) , , .


             ,         - ServerSocket              ,                   .

:


1) .
2) .
3) , ( ) , .
4) .


, . IDE . :


  • 1) .

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class TestAsServer {

/**
 * 
 * @param args
 * @throws InterruptedException
 */
    public static void main(String[] args) throws InterruptedException {
//      3345

        try (ServerSocket server= new ServerSocket(3345);){
//         - "client"                                   
                Socket client = server.accept();

//         -             
                System.out.print("Connection accepted.");

//       ,       

                //    
                DataInputStream in = new DataInputStream(client.getInputStream());
                System.out.println("DataInputStream created");

                //    
                DataOutputStream out = new DataOutputStream(client.getOutputStream());
                System.out.println("DataOutputStream  created");

//       ,                    
                while(!client.isClosed()){

                System.out.println("Server reading from channel");

//      (inputstream)                  
                String entry = in.readUTF();

//                   
                System.out.println("READ from client message - "+entry);

//                  
                System.out.println("Server try writing to channel");

//                    - quit  
                if(entry.equalsIgnoreCase("quit")){
                    System.out.println("Client initialize connections suicide ...");
                    out.writeUTF("Server reply - "+entry + " - OK");                
                    Thread.sleep(3000);
                    break;
                }

//       -   -  -                  
                out.writeUTF("Server reply - "+entry + " - OK");                
                System.out.println("Server Wrote message to client.");

//     (       ,       ,       ,    - flush()                      
                out.flush();    

                }

//    -                
                System.out.println("Client disconnected");
                System.out.println("Closing connections & channels.");

                //     !
                in.close();
                out.close();

                //        !
                client.close();

                //        
                //        
                //           
                server.close();
                System.out.println("Closing connections & channels - DONE.");
            } catch (IOException e) {
                e.printStackTrace();
        }
    }
}

  • 2) .

server.accept(); . , . - (! localhost, , , !). enter , . . :


import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;

public class TestASClient {

    /**
     * 
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {

//                   
        try(Socket socket = new Socket("localhost", 3345);  
                BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
                DataOutputStream oos = new DataOutputStream(socket.getOutputStream());
                DataInputStream ois = new DataInputStream(socket.getInputStream()); )
        {

            System.out.println("Client connected to socket.");
            System.out.println();
            System.out.println("Client writing channel = oos & reading channel = ois initialized.");            

//                 
                while(!socket.isOutputShutdown()){

//                            
                    if(br.ready()){

//   -                       
            System.out.println("Client start writing in channel...");
            Thread.sleep(1000);
            String clientCommand = br.readLine();

//                     
            oos.writeUTF(clientCommand);
            oos.flush();
            System.out.println("Clien sent message " + clientCommand + " to server.");
            Thread.sleep(1000);
//                

//                
            if(clientCommand.equalsIgnoreCase("quit")){

//                  
                System.out.println("Client kill connections");
                Thread.sleep(2000);

//                    
                if(ois.available()!=0)      {   
                    System.out.println("reading...");
                    String in = ois.readUTF();
                    System.out.println(in);
                            }

//                       
                break;              
            }

//                   
            System.out.println("Client sent message & start waiting for data from server...");          
            Thread.sleep(2000);

// ,      (          )           
            if(ois.available()!=0)      {   

//              ois ,                             
            System.out.println("reading...");
            String in = ois.readUTF();
            System.out.println(in);
                    }           
                }
            }
//        
            System.out.println("Closing connections & channels on clentSide - DONE.");

        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

  • 3)

!? , , ? accept() . . ( Runnable? ExecuteServices). :


  • :

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author mercenery
 *
 */
public class MultiThreadServer {

    static ExecutorService executeIt = Executors.newFixedThreadPool(2);

    /**
     * @param args
     */
    public static void main(String[] args) {

        //     3345          
        try (ServerSocket server = new ServerSocket(3345);
                BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
            System.out.println("Server socket created, command console reader for listen to server commands");

            //         
            while (!server.isClosed()) {

                //        
                // 
                if (br.ready()) {
                    System.out.println("Main Server found any messages in channel, let's look at them.");

                    //   - quit     
                    //       
                    String serverCommand = br.readLine();
                    if (serverCommand.equalsIgnoreCase("quit")) {
                        System.out.println("Main Server initiate exiting...");
                        server.close();
                        break;
                    }
                }

                //         
                //       - "clientDialog" 
                //  
                Socket client = server.accept();

                //        
                //          
                //  Runnable(    Callable)
                //   =  - MonoThreadClientHandler  
                //     
                executeIt.execute(new MonoThreadClientHandler(client));
                System.out.print("Connection accepted.");
            }

            //        
            executeIt.shutdown();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

  • Runnable :

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class MonoThreadClientHandler implements Runnable {

    private static Socket clientDialog;

    public MonoThreadClientHandler(Socket client) {
        MonoThreadClientHandler.clientDialog = client;
    }

    @Override
    public void run() {

        try {
            //     ,  

            //    
            DataInputStream in = new DataInputStream(clientDialog.getInputStream());
            System.out.println("DataInputStream created");

            //    
            DataOutputStream out = new DataOutputStream(clientDialog.getOutputStream());
            System.out.println("DataOutputStream  created");

            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //    //
            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

            //       ,   
            //  
            while (!clientDialog.isClosed()) {
                System.out.println("Server reading from channel");

                //       (inputstream) 
                //       
                String entry = in.readUTF();

                //    
                System.out.println("READ from clientDialog message - " + entry);

                //       
                //       - quit   
                if (entry.equalsIgnoreCase("quit")) {

                    //       
                    //  
                    System.out.println("Client initialize connections suicide ...");
                    out.writeUTF("Server reply - " + entry + " - OK");
                    Thread.sleep(3000);
                    break;
                }

                //       -   -
                //    

                System.out.println("Server try writing to channel");
                out.writeUTF("Server reply - " + entry + " - OK");
                System.out.println("Server Wrote message to clientDialog.");

                //    
                out.flush();

                //       
            }

            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //    //
            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

            //    -   
            System.out.println("Client disconnected");
            System.out.println("Closing connections & channels.");

            //     !
            in.close();
            out.close();

            //         
            clientDialog.close();

            System.out.println("Closing connections & channels - DONE.");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

, ( ) Runnable :


  • 4) .

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {

    // private static ServerSocket server;

    public static void main(String[] args) throws IOException, InterruptedException {

        //          -
        // 10-.
        ExecutorService exec = Executors.newFixedThreadPool(10);
        int j = 0;

        //        10   Runnable
        // ,
        //   -  
        while (j < 10) {
            j++;
            exec.execute(new TestRunnableClientTester());
            Thread.sleep(10);
        }

        //  
        exec.shutdown();
    }
}

TestRunnableClientTester() , , :


import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class TestRunnableClientTester implements Runnable {

    static Socket socket;

    public TestRunnableClientTester() {
        try {

            //         
            socket = new Socket("localhost", 3345);
            System.out.println("Client connected to socket");
            Thread.sleep(2000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {

        try (

                //        , 
                //    
                //  try-with-resources 
                DataOutputStream oos = new DataOutputStream(socket.getOutputStream());
                DataInputStream ois = new DataInputStream(socket.getInputStream())) {
            System.out.println("Client oos & ois initialized");

            int i = 0;
            //   
            while (i < 5) {

                //       
                //   
                oos.writeUTF("clientCommand " + i);

                //        
                oos.flush();

                //         
                // 
                Thread.sleep(10);
                System.out.println("Client wrote & start waiting for data from server...");

                //       
                //     ois ,  
                // 
                System.out.println("reading...");
                String in = ois.readUTF();
                System.out.println(in);
                i++;
                Thread.sleep(5000);

            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

, , .


P.S. , .


.

Original source: habrahabr.ru (comments, light).

https://habrahabr.ru/post/330676/

:  

: [1] []
 

:
: 

: ( )

:

  URL