即使队列未满,Java Serversocket也会拒绝连接

时间:2014-04-24 19:36:11

标签: java networking serversocket connectexception

您好我正在尝试在java中设置ServerSocket并且我将积压级别保持为默认值50.我有5个客户端几乎在同一时间尝试连接到服务器。有时一切都很顺利,有时客户端的一些连接被服务器拒绝。我已经尝试将积压值增加到100但没有运气。我正在使用Ubuntu 13.10。有什么想法吗?

package networkmodule;

import iomodule.FileHandler;
import java.io.*;
import java.net.*;
import java.util.*;

public class FileReceiveServer implements Runnable {

private ServerSocket server;
private int receiveport;
private boolean isMaster;
private boolean isStats;
private ArrayList<Thread> clientThreads;
private int totalClients;
private int clientsReceived;

public FileReceiveServer(int receiveport, boolean isMaster, boolean isStats) {
    this.receiveport = receiveport;
    this.isMaster = isMaster;
    this.isStats = isStats;
    clientThreads = new ArrayList<Thread>();
    if (isMaster && !isStats) {
        totalClients = ((Hashtable<String, String>) FileHandler.loadObject("clientstats")).size();
        clientsReceived = 0;
    }
    try {
        server = new ServerSocket(receiveport);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void run() {
    try {
        while (true) {
            Socket clientSocket = server.accept();
            Thread newClientThread = new Thread(new FileReceiverThread(clientSocket, isMaster, isStats));
            clientThreads.add(newClientThread);
            newClientThread.start();
            if (isMaster && !isStats) {
                clientsReceived++;
            }
        }
    } catch (IOException e) {
    }
}

public boolean checkThreadCompletion() {
    if (isMaster) {
        if (clientsReceived < totalClients) {
            return false;
        }
        if (clientThreads.size() > 0) {
            for (Thread t : clientThreads) {
                if (t != null) {
                    if (t.isAlive()) {
                        return false;
                    }
                }
            }
            return true;
        }
        return false;
    } else {
        if (clientThreads.size() > 0) {
            for (Thread t : clientThreads) {
                if (t != null) {
                    if (t.isAlive()) {
                        return false;
                    }
                }
            }
            return true;
        }
        return false;
    }
}

public void stopServer() {
    try {
        server.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

这是一个非常简单的代码,我不知道它为什么有时会失败。这里重要的是它有时候并不总是失败,当它失败时,当我尝试用套接字连接到服务器时,它总是在客户端失败:

java.net.ConnectException: Socket Connection Refused

有什么想法吗?

由于

0 个答案:

没有答案