SocketException:资源暂时不可用:recv失败

时间:2013-06-07 20:53:03

标签: java sockets networking

我正在尝试在我的客户端程序和服务器程序之间建立连接,但是当我尝试发送字符串时,我得到错误“SocketException:资源暂时不可用:recv失败”。

我该如何解决这个问题?

更新:我打印severSocket.getInetAddress().getHostName()并打印0.0.0.0。这可能是连接无法正常工作的原因吗?

这是客户:

// CLIENT
public static void main(String[] args) throws IOException
{
    setLookAndFeel(Theme.SEAGLASS);

    Socket clientSocket = null;
    PrintWriter out = null;
    BufferedReader in = null;

    try
    {
        clientSocket = new Socket(InetAddress.getLocalHost().getHostName(), 4321);
        out = new PrintWriter(clientSocket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

        out.println("Hello!"); //This line causes the problem.
    }
    catch (UnknownHostException e)
    {
        System.err.println("Unknown host!");
        System.exit(1);
    }
    catch (IOException e)
    {
        System.err.println("No I/O");
        System.exit(1);
    }

    SwingUtilities.invokeLater(new Runnable()
    {
        public void run()
        {
            createAndShowGUI();
        }
    });

    out.close();
    in.close();
    clientSocket.close();
}

这是服务器:

// SERVER
public static void main(String[] args)
{
    SwingUtilities.invokeLater(new Runnable()
    {
        public void run()
        {
            createAndShowGUI();
        }
    });

    try
    {
        serverSocket = new ServerSocket(4321);
    } catch (IOException e)
    {
        System.err.println("Could not listen on port 4321");
        System.exit(-1);
    }

    try
    {
        clientSocket = serverSocket.accept();
    } catch (IOException e)
    {
        System.err.println("Accept failed: 4321");
        System.exit(-1);
    }

    try
    {
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        out = new PrintWriter(clientSocket.getOutputStream(), true);
    } catch (IOException e)
    {
        System.err.println("No I/O.");
        e.printStackTrace();
        System.exit(-1);
    }

    while (true)
    {
        try
        {
            String line = in.readLine(); //SocketException here.
            textArea.append(line);
        } catch (IOException e)
        {
            System.err.println("Read failed.");
            e.printStackTrace();
            System.exit(-1);
        }
    }
}

提前感谢您的帮助!

0 个答案:

没有答案