IO建立Socket通訊中慎用BufferReader中的readLine()

lonecloud發表於2018-05-09

在編寫Socket的Demo的時候,在Server中使用BufferReader獲取從客服端傳送過來的內容

package cn.lonecloud.socket;

import cn.lonecloud.thread.factory.TraceThreadPool;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author lonecloud
 * @version v1.0
 * @date 下午5:11 2018/5/9
 */
public class SocketServer {
     //建立執行緒
    static ExecutorService service = new ThreadPoolExecutor(0, 10, 60L, TimeUnit.SECONDS, new SynchronousQueue<>());
   //處理訊息類
    static class HandlerMsg implements Runnable {
        //客戶端socket
        Socket clientSocket;

        public HandlerMsg(Socket clientSocket) {
            this.clientSocket = clientSocket;
        }

        @Override
        public void run() {
            BufferedReader reader = null;
            PrintWriter pr = null;
            try {
               //獲取訊息
                reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                pr = new PrintWriter(clientSocket.getOutputStream(), true);
                Instant now = Instant.now();
                String s = null;
                while ((s = reader.readLine()) != null) {
                    pr.append(s);
                }
                pr.close();
                reader.close();
                clientSocket.close();
                System.out.println("spend "+(Instant.now().getNano()-now.getNano()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

  client

 

package cn.lonecloud.socket;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author lonecloud
 * @version v1.0
 * @date 下午5:24 2018/5/9
 */
public class SocketClient {

    public static void main(String[] args) throws IOException {
        Socket socket=new Socket();
     //連結 socket.connect(new InetSocketAddress("localhost",8000)); PrintWriter printWriter = new PrintWriter(socket.getOutputStream(),true); //獲取輸入
     Scanner scanner=new Scanner(System.in); String s = scanner.nextLine(); //必須使用println不然會一直卡在這裡
     printWriter.println(s); printWriter.flush();
     //讀取資料 InputStream inputStream = socket.getInputStream(); BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream)); //列印
     System.out.println("from server"+reader.readLine()); System.out.flush(); printWriter.close(); reader.close(); socket.close(); } }

  Main

package cn.lonecloud.socket;

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

/**
 * @author lonecloud
 * @version v1.0
 * @date 下午5:21 2018/5/9
 */
public class ServerMain {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = null;
        Socket clientSocket = null;
        serverSocket = new ServerSocket(8000);
        while (true) {
            clientSocket = serverSocket.accept();
            System.out.println(clientSocket.getRemoteSocketAddress() + "connect");
            SocketServer.service.execute(new SocketServer.HandlerMsg(clientSocket));
        }
    }
}

  出現如下問題,如果Socket中如果對採用如下程式碼

while ((s = reader.readLine()) != null) {
                    pr.append(s);
                }

  如果其在客戶端不採用println列印換行符,將導致客戶端與伺服器端一直處於工作狀態,因為其一直都未接收到"\n"

相關文章