BindException多线程服务器

时间:2014-02-23 00:22:28

标签: java multithreading sockets exception binding

我有3台服务器,我在这些服务器上运行以下代码。然而其中一个给出了错误:

Exception in thread "main" java.net.BindException: Address already in use
    at java.net.PlainSocketImpl.socketBind(Native Method)
    at java.net.AbstractPlainSocketImpl.bind(Unknown Source)
    at java.net.ServerSocket.bind(Unknown Source)
    at java.net.ServerSocket.<init>(Unknown Source)
    at java.net.ServerSocket.<init>(Unknown Source)
    at MultiThreadServer.main(MultiThreadServer.java:22)

即使我停止使用命令“ps -ef | grep java | grep -v grep | awk'{print $ 2}'| xargs kill -9”运行程序,它仍然会给出相同的异常。 代码如下:

public class MultiThreadServer implements Runnable {
Socket csocket;
MultiThreadServer(Socket csocket) {
    this.csocket = csocket;
}

public static void main(String args[]) 
        throws Exception {
    ServerSocket ssock = new ServerSocket(8879);
    System.out.println("Listening");
    while (true) {
        Socket sock = ssock.accept();
        System.out.println("Connected");
        new Thread(new MultiThreadServer(sock)).start();
    }

}
public void run() {..}

1 个答案:

答案 0 :(得分:1)

该端口可能已在使用中。尝试使用其他端口。