【问题标题】:java.net.BindException: Address already in use: JVM_Bindjava.net.BindException:地址已在使用中:JVM_Bind
【发布时间】:2015-10-30 02:38:10
【问题描述】:

服务器程序:

 import java.io.*;
 import java.net.*;
 class Server{
   public static void main(String args[]){
    try{
        ServerSocket ss = new ServerSocket(8080);
        Socket s = ss.accept();
        DataInputStream dis = new DataInputStream(s.getInputStream());
        String str = (String)dis.readUTF();
        System.out.println("Message : "+str);
        ss.close();
    }catch(Exception e){
        System.out.println(e);
    }
  }
}

客户程序:

import java.io.*;
import java.net.*;
class client{
  public static void main(String args[]){
    try{
        Socket s = new Socket("localhost",8080);
        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        dos.writeUTF("Hello friend ");
        dos.flush();
        dos.close();
        s.close();
    }catch(Exception e){
        e.printStackTrace();
      }
    }
 }

当我执行这个程序时。我收到类似“java.net.BindException:地址已在使用:JVM_Bind”之类的错误,但在它正常工作之前。请问有人帮我解决这个问题吗?

【问题讨论】:

  • 也许同一进程的两个实例同时运行,试图绑定到同一个端口两次?

标签: java server networking sockets


【解决方案1】:

如果您多次重新启动程序的服务器端,则可能存在 TIME_WAIT 中的套接字,从而阻止您再次侦听端口 8080。

你需要设置启用重用选项(socket option SO_REUSEADDR)如下:

ServerSocket ss = new ServerSocket();
ss.setReuseAddress(true);
ss.bind(new InetSockAddress(8080));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-12
    • 2014-11-02
    • 1970-01-01
    • 1970-01-01
    • 2012-09-26
    相关资源
    最近更新 更多