java-单线程阻塞IO模型案例

单线程阻塞IO模型每次只能处理一个连接,后面的连接被阻塞掉,需要前面的连接退出后,服务器才能处理下一个连接请求。

package com.io;

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

/**
 * @author: 
 * @Date: 2020/05/15
 * @Description:
 */
public class SignleThreadBlockingIO {

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9688);
        while (true) {
            Socket clientSocket = serverSocket.accept();
            try {
                process(clientSocket);
            } catch (Exception ex) {
                ex.printStackTrace();
                clientSocket.close();
            }
        }
    }

    /**
     * 处理连接
     * @param socket
     * @throws Exception
     */
    private static void process(Socket socket) throws Exception {
        System.out.println("client socket connect:" + socket.getRemoteSocketAddress());
        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        String readLine;
        while ((readLine = reader.readLine()) != null) {
            System.out.println("message from client:" + readLine);
            if ("over".equals(readLine)) {
                break;
            } else {
                writer.write(readLine);
                writer.newLine();
                writer.flush();
            }
        }
    }
}
package com.io;

import com.asyn.temp.Bu;
import com.thread.communication.example.Product;

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

/**
 * @author: 
 * @Date: 2020/05/15
 * @Description:
 */
public class ClientSocket {

    public static void main(String[] args) throws IOException {
        try {
            Socket socket = new Socket("localhost", 9688);
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            PrintWriter writer = new PrintWriter(socket.getOutputStream());
            BufferedReader socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String readLine;
            while ((readLine = reader.readLine()) != null) {
                writer.println(readLine);
                writer.flush();
                System.out.println("message from server:" + socketReader.readLine());
                if (readLine.equals("over")) {
                    break;
                }
            }
            writer.close();
            socketReader.close();
            reader.close();
            socket.close();
        } catch (IOException e) {
            System.out.println("can't listen to:" + e);
        }
    }
}

在这个案例中,会在调用处理连接方法时阻塞。如果有新的连接只能等待上一个连接处理结束。

你可能感兴趣的:(socket,java)