java Socket Client Server docking correct wording (BIO)

Prior written in the work of some of Socket client and server code, but there was no time to investigate them, not only an error, had one attitude, a deep understanding of its details, write code has also unaware of the problems, but the order of business as well as docking side docking code does not appear out of line situation so the question should not be exposed.

First, by doing a single-threaded server is a Socket BIO practice, this approach will lead to the server can only receive a sum request Meanwhile, the performance is very poor

Now I look at BIO post code, needy students can refer to

Server

public  class SocketIO {
     // the client code, client and server transmits the encoded the same, the server process without performing a special decoding 
    Private  static  Final String CLIENTENCODEING = "UTF-. 8" ;
     Private  static  Final  int PORT = 7777 ;
     Private  static of AtomicInteger = COUNT new new of AtomicInteger (); 

    public  static  void main (String [] args) throws IOException { 
        the serverSocket serverSocket = new new the serverSocket (pORT); 
        System.out.println ( "start port:" + pORT);
         the while (to true ) { 
            the Socket Socket = null ; 
            the InputStream inputStream = null ; 
            the OutputStream the outputStream = null ;
             the try {
                 // will block where no data, i.e. accept data call accept event trigger method
                 // when a connection comes in, a second connections could not come, because the single-threaded, also blocked in the following read, the thread can no longer continue to accept back on the waiting 
                socket = serverSocket.accept ();
                 int ccount = count.incrementAndGet (); 
                System.out.println ( "the new client is connected, the current No." + ccount + "" + System.currentTimeMillis ());

                inputStream = new BufferedInputStream(socket.getInputStream());
                outputStream = new BufferedOutputStream(socket.getOutputStream());

                //读取正文内容
                byte[] flush = new byte[1024];
                int length = 0;
                StringBuffer rec = new StringBuffer();
                while ((length = inputStream.read(flush)) != -1) {
                    rec.append(new String(flush, 0, length));
                }
                //Writing 2
                 // client is not notified off socket.shutdownOutput (); while, by following this method, the method does not notify the die closing cycle read
                 // Available () method can be known before the first data stream read and write operations have how many bytes can be read
                 // but if the client sends batches may be a problem, may not be the second batch of data acquisition and subsequent
                 // it's better to let the client informed about
 //                 int COUNT = 0;
 //                 the while (COUNT == 0) {
 //                     COUNT = inputStream.available ();
 //                 }
 //                 byte [] = the flush new new byte [COUNT];
 //                 InputStream.read (the flush);
 //                 String String new new REC = (flush, 0, count, CLIENTENCODEING );

                Back String = "[" ccount + + "]" + UUID.randomUUID () + "" ; 
                System.out.println ( "the received data:" + rec.toString () + "about to return data:" + Back);
                 // return data 
                OutputStream.write (back.getBytes (), 0 , back.getBytes () length.); 
                outputStream.flush (); 
            } the catch (Exception E) { 
                e.printStackTrace (); 
            } the finally { 
                Close (Socket , inputStream, the outputStream); 
            } 
        } 
    } 

    Private  static  void close(Socket socket,
            InputStream inputStream,
            OutputStream outputStream) throws IOException {
        if (outputStream != null) {
            outputStream.close();
        }
        if (inputStream != null) {
            inputStream.close();
        }
        if (socket != null) {
            socket.close();
        }
    }
}

Column few points need attention:

1, read by the read method is preferably sent by the client content, a case where the code available I Found client will lose the message transmitted multiple times, unreliable.

2, is best fit by the InputStream stream Buffered * Stream buffer, using the OutputStream

3, remember to flush after write

4, close the stream

Client

  //服务端编码
    private static final String SERVERENCODEING = "UTF-8";

    public static void main(String[] args){
        for (int i = 0; i < 1; i++) {
            new Thread(() -> {
                try {
                    doo();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }

    public static void doo() throws{IOException 
        the Socket Socket = null ; 
        the InputStream in = null ; 
        the OutputStream OUT = null ; 
        String MSG = "hello hello hello good!" ;
         The try {
             // send data 
            Socket = new new the Socket ( "127.0.0.1", 7777 ) ; 
            OUT = new new BufferedOutputStream The (Socket.getOutputStream ()); 
            in = new new BufferedInputStream (Socket.getInputStream ()); 
            out.write (Msg.getBytes ()); 
            out.flush (); 

            out.write ( "a little bit" .getBytes ()); 
            out.flush (); 
//             // Any of the close input stream or output stream () will cause the Socket close but not close and cause the server can not receive to -1
 //             the out.close (); 
            socket.shutdownOutput (); 

            // read the text content 
            byte [] = the flush new new  byte [1024 ];
             int length = 0 ; 
            the StringBuffer REC = new new the StringBuffer ();
             the while (( ! = in.read length (the flush)) = -1 ) { 
                rec.append ( new new String (the flush, 0, length, SERVERENCODEING)); //In the server transmission coding standard 
             }
            System.out.println ( "client received a reply:" + rec.toString ()); 
            in.close (); 
            the Socket.close (); 
        } the catch (IOException E) { 
            e.printStackTrace (); 
        } the finally { 
            Close (Socket, in, OUT); 
        } 
    } 

    Private  static  void Close (the Socket Socket, 
                              the inputStream inputStream, 
                              the OutputStream the outputStream) throws IOException {
         IF (the outputStream =! null ) {
            outputStream.close();
        }
        if (inputStream != null) {
            inputStream.close();
        }
        if (socket != null) {
            socket.close();
        }
    }

Column few points need attention:

1, out.close (); any input stream or output stream close () will cause the Close Socket Close but not the service can not receive the turn leads to -1

2, using socket.shutdownOutput (); notification sent by the server to complete

3, remember to flush after write

4, close the stream

Guess you like

Origin www.cnblogs.com/zxporz/p/10972727.html