java socket服务器 ,socket.getInputStream()读取时阻塞

贴代码:

 
   
public static void main(String[] args){
 
  
        MessageDeal deal = new MessageDeal();
        deal.init();
    }
    public void init(){
        try {
            ServerSocket serverSocket = new ServerSocket(port);
            Socket socket = null;
            while (true){
                socket = serverSocket.accept();
                DealThread dealThread = new DealThread(socket);
                new Thread(dealThread).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    private class DealThread implements Runnable{
        private Socket socket;
        public DealThread(Socket socket){
            this.socket = socket;
        }
        @Override
        public void run() {
            BufferedWriter writer = null;
            InputStream in = null;
            BufferedReader reader = null;
            OutputStream os = null;
            try {
                System.out.println("开始读流");
                in = socket.getInputStream();
                /*reader = new BufferedReader(new InputStreamReader(in,"GBK"));
                char[] bt = new char[8];
                do  {
                    if ((reader.read(bt))!=-1){
//                        System.out.println(data);
                    }
                }while (reader.ready());
                socket.shutdownInput();
                System.out.println("读取完毕");*/
                BufferedInputStream bis = new BufferedInputStream(in);
                int n = 0;
                while ( (n =bis.read()) != -1){
                    System.out.println(n);
                }
                os = socket.getOutputStream();
                writer = new BufferedWriter(new OutputStreamWriter(os, "GBK"));
                writer.write(successMsg);
                writer.flush();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                try {
                    if (reader != null) reader.close();
                    if (in != null) in.close();
                    if (writer != null) writer.close();
                    if (os != null) os.close();
                    if (socket != null) socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
使用阻塞javaio读取socket流时,在红色部分进行while循环时始终无法读到-1,使用各种XXStream和XXReader都不行,网上借鉴的还是不靠谱,
反复查看java doc也没能解决

参考一下博客:http://blog.csdn.net/qq_27680317/article/details/72899394

解释为:socket流没有结束符。。。

虽然不知道这个解释对不对,但是使用注释掉的代码替换红色部分,正常运行

使用javaio读取socket接收的无协议传输流,使用ready()方法可以解决一次性完整读取问题

你可能感兴趣的:(java socket服务器 ,socket.getInputStream()读取时阻塞)