IO伪异步实现

伪异步的实现,通过多线程,也会阻塞,等待连接

1、创建TcpServer类

package com.cppdy.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//tcp服务端
public class TcpServer {

    public static void main(String[] args) throws Exception {
        
        ExecutorService pool = Executors.newCachedThreadPool();

        System.out.println("tcp服务端启动啦……");
        ServerSocket serverSocket = new ServerSocket(8080);
        //伪异步的实现,通过多线程
        while(true) {
            // 也会阻塞在这里,等待连接
            Socket accept = serverSocket.accept();
            pool.execute(new Runnable() {
                
                @Override
                public void run() {
                    try {

                        InputStream inputStream = accept.getInputStream();

                        byte[] bytes = new byte[1024];

                        int length = inputStream.read(bytes);

                        String result = new String(bytes, 0, length);

                        System.out.println("服务端接收到客户端发送的消息:" + result);

                        OutputStream outputStream = accept.getOutputStream();

                        PrintWriter printWriter = new PrintWriter(outputStream);

                        printWriter.println("服务器收到消息了,这是服务器自动反馈……");

                        printWriter.flush();

                        accept.shutdownOutput();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } 
                }
            });
        }
        
    }

}

2、创建TcpClient类

package com.cppdy.tcp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

//tcp客户端
public class TcpClient {

    public static void main(String[] args) throws Exception {

        Socket socket = new Socket("127.0.0.1", 8080);

        try {
            OutputStream outputStream = socket.getOutputStream();

            String msg = "吹泡泡的魚";

            outputStream.write(msg.getBytes());

            System.out.println("客户端发送消息完毕……");

            InputStream inputStream = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

            String result = br.readLine();

            System.out.println("客户端==》服务器返回的结果:" + result);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            socket.close();
        }
    }

}

 

posted @ 2018-11-30 23:22  知识追求者  阅读(259)  评论(0编辑  收藏  举报