日期:2014-05-20  浏览次数:20891 次

【Java TCP阻塞问题...在线等...】有没有好心人帮我看看为什么这段代码会阻塞啊?
最近看了一本《Java TCP/IP Socket》书中讲解了关于Socket的一些内容,其中看到关于阻塞的内容后,有点想不明白,大家能不能帮我看看代码,为什么会出现阻塞啊?

例子中有两种情况,情况1:不会出现阻塞;情况2:会出现阻塞;

代码如下:

//客户端
public class CompressClient
{
    public static final int BUFSIZE = 256;

    public static void main(String[] args) throws IOException
    {
        InetAddress inetAddr = InetAddress.getLocalHost();
        int port = 8888;
        String fileName = "D:\\杂乱\\桌面.jpg";

        FileOutputStream fileOut = new FileOutputStream(fileName + ".gz");
        final FileInputStream fileIn = new FileInputStream(new File(fileName));

        final Socket sock = new Socket(inetAddr, port);

        // 情况一:不会出现阻塞
        // Thread thread = new Thread()
        // {
        // @Override
        // public void run()
        // {
        // try
        // {
        // sendBytes(sock, fileIn);
        // }
        // catch (IOException e)
        // {
        // e.printStackTrace();
        // }
        // }
        // };

        // thread.start();

        // 情况二:会出现阻塞
        sendBytes(sock, fileIn);

        // 接收压缩服务器信息
        InputStream sockIn = sock.getInputStream();
        int bytesRead;
        byte[] buffer = new byte[BUFSIZE];
        while ((bytesRead = sockIn.read(buffer)) != -1)
        {
            fileOut.write(buffer, 0, bytesRead);
            System.out.print("R");
        }
        System.out.println();

        fileIn.close();
        fileOut.close();
        sock.close();
    }

    private static void sendBytes(Socket socket, InputStream fileIn)
            throws IOException
    {
        OutputStream sockOut = socket.getOutputStream();
        int bytesRead = 0;
        byte[] buffer = new byte[BUFSIZE];
        while ((bytesRead = fileIn.read(buffer)) != -1)
        {
            sockOut.write(buffer, 0, bytesRead);
            System.out.print("W");
        }
        System.out.println("\nClient send data complete!");
        socket.shutdownOutput();
        System.out.println("Client is deadlock? No");
    }
}


//服务端
public class TCPEchoServerExecutor
{
    public static void main(String[] args) throws IOException
    {
        int echoServProt = 8888;

        ServerSocket servSock = new ServerSocket(echoServProt);
        Logger logger = Logger.getLogger("practical");
        Executor service = Executors.newCachedThreadPool();

        while (true)