Java - 地址已在使用中(网络绑定(bind))

标签 java sockets networking port

我知道这个问题已经被问了一百万次,但我还没有找到像我这样的情况。我有一个简单的 java 聊天应用程序,几个月前还在工作,我又回来了,现在我遇到了问题。当我在 Eclipse 中运行 server.java 时,一切正常。当我之后运行 client.java 文件时,我得到以下信息:

Exception in thread "main" java.net.BindException: Address already in use: NET_Bind
    at java.base/java.net.DualStackPlainSocketImpl.bind0(Native Method)
    at java.base/java.net.DualStackPlainSocketImpl.socketBind(Unknown Source)
    at java.base/java.net.AbstractPlainSocketImpl.bind(Unknown Source)
    at java.base/java.net.PlainSocketImpl.bind(Unknown Source)
    at java.base/java.net.ServerSocket.bind(Unknown Source)
    at java.base/java.net.ServerSocket.<init>(Unknown Source)
    at java.base/java.net.ServerSocket.<init>(Unknown Source)
    at chat.Server.main(Server.java:18)

我已经终止了 eclipse 中的所有启动,在命令提示符中找到了 PID 并将其杀死,尝试更改端口号,但每次尝试运行我的程序时,我仍然得到仍在使用的地址。我还尝试在命令提示符下运行 netstat -a 命令来查找正在使用的端口号,我尝试过的端口号都没有。

Server.java(包含服务器代码以及客户端处理程序类):
public class Server 
{
    //vector to store active clients, static so threads share the vector of clients
    static Vector<ClientHandler> activeUsers = new Vector<>();

    public static void main(String[] args) throws IOException 
    {
        ServerSocket serverSocket = new ServerSocket(1234); //server is listening on port 1234
        Socket s;   
        while (true) //infinite loop for getting client request
        {
            s = serverSocket.accept(); //accept the incoming request

            //obtain input and output streams
            DataInputStream dis = new DataInputStream(s.getInputStream());
            DataOutputStream dos = new DataOutputStream(s.getOutputStream());

            String username = dis.readUTF(); //username is first thing sent from the client for naming
            ClientHandler newClient = new ClientHandler(s,username , dis, dos); //create a new handler object for handling this client

            //notify currently connected users that a new user has joined
            newClient.notifyUsers(activeUsers, " has joined the server!");

            Thread t = new Thread(newClient); //create a new Thread with this object.
            activeUsers.add(newClient); //add this client to active clients list
            t.start(); //start the thread.
        }//end while


    }//end main
}//end class Server

class ClientHandler implements Runnable 
{
    private String name;
    DataInputStream dis;
    DataOutputStream dos;
    Socket socket;
    boolean isloggedin;


    public ClientHandler(Socket socket, String name, DataInputStream dis, DataOutputStream dos) 
    {
        this.dis = dis; //data input stream
        this.dos = dos; //data output stream
        this.name = name; //client name
        this.socket = socket; //socket
        this.isloggedin=true; //handler is being created so user is logged in
    }
}

客户端.java:
public class Client extends JFrame implements ActionListener
{
    DataInputStream dis = null;
    DataOutputStream dos = null;
    final static int ServerPort = 1234;
    JButton     sendMessage;
    JTextField  messageBox;
    JTextArea   chatBox;
    JButton     logoutButton;
    JButton     activeUsersButton;
    JFrame      newFrame    = new JFrame(".Chat");
    String username;
    Socket s = null;


    public Client(String user)
    {

        this.username = user;
    }

    public void start() throws UnknownHostException, IOException 
    {
        newFrame.setTitle("chat - " + username);

        InetAddress ip = InetAddress.getByName("localhost");

        //establish the connection to the server
        s = new Socket(ip, ServerPort);

        //obtaining input and out streams
        dis = new DataInputStream(s.getInputStream());
        dos =  new DataOutputStream(s.getOutputStream());

        dos.writeUTF(username);

        //readMessage thread
        Thread readMessage = new Thread(new Runnable() 
        {
            @Override
            public void run() 
            {
                while (dos != null && dis != null) {
                    try 
                    {
                        //read the message sent to this client
                        String msg = dis.readUTF();
                        System.out.println(msg);
                        chatBox.append(msg);
                    } //end try
                    catch (IOException e) 
                    {

                        e.printStackTrace();
                    }//end catch
                }//end while
            }//end run
        });
        display();
        readMessage.start();
    }


    //not sure what this needs to do? just to satisfy an error
    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
         Object obj = e.getSource();
           if(obj == sendMessage){ 
                String msg = messageBox.getText();
                try {
                    dos.writeUTF(msg);
                    chatBox.append(username + ": " + msg + "\n"); //place what the user sent in the text box
                    messageBox.setText(""); 
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
           } 
           else{}
    }
}

我省略了按钮代码,因为它只是在套接字上发送/接收消息以及 UI 代码。

最佳答案

当您启动服务器时,端口 1234 上已经有东西在监听:可能是它的先前实例;或者可能在 TIME_WAIT 中仍然有一个套接字。用 SO_REUSEADDR 试试,这样:

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

注意你还有另一个问题。您忽略了流的结束。鉴于您正在调用 readUTF() ,你需要捕获EOFException并退出循环并在抛出时关闭套接字。 EOS 不会神奇地使输入或输出流为空。

关于Java - 地址已在使用中(网络绑定(bind)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51204697/

相关文章:

java - Recyclerview 上类似 Facebook react 的动画

java - android加载库失败

c - getaddrinfo 中的 malloc 校验和不正确

c++ - 套接字调用在同时执行的两个或多个线程上提供重复的文件描述符(竞争条件)

azure - 无法使用 cli 创建 azure 虚拟机

networking - UDP数据包可以被分割成几个较小的数据包吗

java - 如何从 Java 项目运行 Docker 容器?

java - 无法刷新 android 中的 ListView - notificationDataSetChanged() 不执行任何操作

c++ - pselect() 与循环中的 accept()

android - Android 中的数据包级网络