即使我关闭套接字也得到java.net.BindException

时间:2014-11-08 08:09:54

标签: java sockets

我是套接字编程的新手,只是尝试一个小程序来掌握套接字的工作方式。有客户端和服务器,我只是想从服务器和显示器加载一些字符串。但是每次我创建一个服务器Socket时,我得到java.net.BindException,即使我手动清理finally块中的所有资源。看看下面的代码,请建议一些可能导致此问题的编辑。我正在使用Eclipse。

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

public class AdviceServer {

String[] adviceList = {
        "Take smaller bites",
        "Go for the tight jeans. No they do NOT" + "make you look fat.",
        "One word: inappropriate",
        "Just for today, be honest. Tell your"
                + "boss what you *really* think",
        "You might want to rethink that haircut." };

public void setUpServer() {

    ServerSocket serverSocket = null;

    try {
        if (serverSocket == null)
        serverSocket = new ServerSocket(8003);
        int i = 2;

        // Keep looping till we have clients.
        while (true) {
            Socket sock = serverSocket.accept();
            PrintWriter pw = new PrintWriter(sock.getOutputStream());
            pw.write(getRandomAdvice());
            pw.close();
            System.out.println(getRandomAdvice());
        }

     //   serverSocket.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (serverSocket != null) {
            try {
                serverSocket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

public void setUpClient() {

    // Make a socket
    Socket chatSocket = null;
    try {
        chatSocket = new Socket("127.0.0.1", 8003);
        InputStreamReader isr = new InputStreamReader(
                chatSocket.getInputStream());

        // Make a chain stream Buffered Reader
        BufferedReader br = new BufferedReader(isr);

        String text;
        while ((text = br.readLine()) != null) {
            System.out.println(text);
        }

        br.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (chatSocket != null) {
            try {
                chatSocket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }


}

public String getRandomAdvice() {
    return adviceList[(int) (Math.random() * adviceList.length)];

}

public static void main(String[] args) {
    AdviceServer as = new AdviceServer();

    as.setUpClient();
    as.setUpServer();
}
}

任何帮助都会非常感激,因为我已经尝试了几乎所有的事情来纠正这个问题。

3 个答案:

答案 0 :(得分:1)

其他东西已经在端口8003上侦听了。可能是您程序的先前实例,可能还有别的东西。使用netstat找出哪个。

如果是您自己的程序,请将ServerSocket创建更改为:

serverSocket = new ServerSocket();
serverSocket.setReuseAddress(true);
serverSocket.bind(new InetSocketAddress(8003));

答案 1 :(得分:1)

你必须运行你的代码两次,因此得到BindException。在第一次运行时,服务器将运行并侦听端口8003,你将得到ConnectionRefused错误。下次你运行此程序,当您再次运行服务器代码时,客户端将从服务器获取消息,然后是BindException

问题是服务器和客户端在同一主线程上运行。尝试在不同的线程中运行服务器并且首先运行服务器,它将监听客户端的连接。

答案 2 :(得分:0)

问题是您先是初始化客户端然后是服务器。

as.setUpClient();

as.setUpServer();

我认为你这样做是为了让代码运行两次。 首先,你得到拒绝连接,当你第二次得到 BindException 时,你会运行它。 没有关闭以前的控制台。

同时检查是否有任何其他进程在同一端口上绑定。 如果你在Windows上运行

nestat -ano

如果您看到端口 8003 ,请使用任务管理器引用该pid并将其终止。

由于您已经尝试过其他端口,我猜您的问题是第一点所述。

即使你要扭转它 代码中的顺序

as.setUpServer();

as.setUpClient();

因为你的  Socket sock = serverSocket.accept();阻止api。您的客户代码,即 as.setUpClient();将不会被召唤。

将其拆分为两个文件客户端和服务器。 先运行服务器然后运行客户端。它会起作用。

做一些这样的事情:

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

public class AdviceServer {

    String[] adviceList = {
            "Take smaller bites",
            "Go for the tight jeans. No they do NOT" + "make you look fat.",
            "One word: inappropriate",
            "Just for today, be honest. Tell your"
                    + "boss what you *really* think",
            "You might want to rethink that haircut." };

    public void setUpServer() {

        ServerSocket serverSocket = null;

        try {
            if (serverSocket == null)
                serverSocket = new ServerSocket(8003);
            int i = 2;

            // Keep looping till we have clients.
            while (true) {
                Socket sock = serverSocket.accept();
                PrintWriter pw = new PrintWriter(sock.getOutputStream());
                pw.write(getRandomAdvice());
                pw.close();
                System.out.println(getRandomAdvice());
            }

            // serverSocket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    public String getRandomAdvice() {
        return adviceList[(int) (Math.random() * adviceList.length)];

    }

    public static void main(String[] args) {
        AdviceServer as = new AdviceServer();

        as.setUpServer();

    }
}





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

public class AdviceClient {

    public void setUpClient() {

        // Make a socket
        Socket chatSocket = null;
        try {
            chatSocket = new Socket("127.0.0.1", 8003);
            InputStreamReader isr = new InputStreamReader(
                    chatSocket.getInputStream());

            // Make a chain stream Buffered Reader
            BufferedReader br = new BufferedReader(isr);

            String text;
            while ((text = br.readLine()) != null) {
                System.out.println(text);
            }

            br.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (chatSocket != null) {
                try {
                    chatSocket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }


    }

    public static void main(String[] args){

        AdviceClient client = new AdviceClient();
        client.setUpClient();
    }
}