netty学习之BIO(一)

BioServer - 

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

/**
 * Description:
 *
 * @author maduar maduar@163.com
 * @version 1.1.1 02/04/2019
 */
public class BioServer {

    private static final int PORT = 8088;

    public static void main(String[] args) {

        try (ServerSocket serverSocket = new ServerSocket(PORT)) {

            Socket socket;

            while (true) {
                socket = serverSocket.accept();
                new Thread(new BioHandler(socket)).start();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;

/**
 * Description:
 *
 * @author maduar maduar@163.com
 * @version 1.1.1 02/04/2019
 */
public class BioHandler implements Runnable {

    private Socket socket;

    public BioHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try (
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
                PrintWriter printWriter = new PrintWriter(this.socket.getOutputStream(), true)) {

            String body;

            while ((body = bufferedReader.readLine()) != null && body.length() != 0) {
                System.out.println("receive msg: " + body);
                printWriter.println(new Date().toString());
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

  

 

client

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * Description:
 *
 * @author maduar maduar@163.com
 * @version 1.1.1 02/04/2019
 */
public class Client {

    private static final int PORT = 8088;
    private static final String HOST = "127.0.0.1";

    public static void main(String[] args) {

        try (
                Socket socket = new Socket(HOST, PORT);
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {

            out.println("I am client .");
            String resp = in.readLine();
            System.out.println("current time is :" + resp);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

  

原文地址:https://www.cnblogs.com/maduar/p/10646324.html