0

嗨,我正在尝试在 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

有任何想法吗?

谢谢

4

0 回答 0