2

我知道以下代码可能看起来很粗俗,但我对这些东西很陌生,只是尝试了一切以使其正常工作..

问题:即使我正在使用(可能以错误的方式)一个 CyclicBarrier,一个 - 并且似乎总是相同的 - 线程过早停止并打印出他的向量,在这些“传入连接”消息中的 11 个中留下 1 个不存在. 我的循环的最后一次迭代可能存在严重错误,但我似乎无法找到确切的内容。现在程序只是循环等待处理最后一个连接。

public class VectorClockClient implements Runnable {
/*
 * Attributes
 */

/*
 * The client number is store to provide fast
 * array access when, for example, a thread's own
 * clock simply needs to be incremented.
 */
private int clientNumber;
private File configFile, inputFile;
int[] vectorClock;

/*
 * Constructor
 * @param
 * - File config
 * - int line
 * - File input
 * - int clients
 */
public VectorClockClient(File config, int line, File input, int clients) {
    /*
     * Make sure that File handles aren't null and that
     * the line number is valid.
     */
    if (config != null && line >= 0 && input != null) {
        configFile = config;
        inputFile = input;
        clientNumber = line;
        /*
         * Set the array size to the number of lines found in the
         * config file and initialize with zero values.
         */
        vectorClock = new int[clients];
        for (int i = 0; i < vectorClock.length; i++) {
            vectorClock[i] = 0;
        }
    }
}

private int parsePort() {
    int returnable = 0;
    try {
        FileInputStream fstream = new FileInputStream(configFile.getName());
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine = "";
        for (int i = 0; i < clientNumber + 1; i++) {
            strLine = br.readLine();
        }
        String[] tokens = strLine.split(" ");
        returnable = Integer.parseInt(tokens[1]);
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println("[" + clientNumber + "] returned with " + returnable + ".");
    return returnable;
}

private int parsePort(int client) {
    int returnable = 0;
    try {
        FileInputStream fstream = new FileInputStream(configFile.getName());
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine = "";
        for (int i = 0; i < client; i++) {
            strLine = br.readLine();
        }
        String[] tokens = strLine.split(" ");
        returnable = Integer.parseInt(tokens[1]);
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    return returnable;
}

private int parseAction(String s) {
    int returnable = -1;
    try {
        FileInputStream fstream = new FileInputStream(configFile.getName());
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String[] tokens = s.split(" ");
        if (!(Integer.parseInt(tokens[0]) == this.clientNumber + 1)) {
            return -1;
        }
        else {
            if (tokens[1].equals("L")) {
                vectorClock[clientNumber] += Integer.parseInt(tokens[2]);
            }
            else {
                returnable = Integer.parseInt(tokens[2]);
            }
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    return returnable;
}

/*
 * Do the actual work.
 */
public void run() {
    try {
        InitClients.barrier.await();
    }
    catch (Exception e) {
        System.out.println(e);
    }
    int port = parsePort();
    String hostname = "localhost";
    String strLine;
    ServerSocketChannel ssc;
    SocketChannel sc;
    FileInputStream fstream;
    DataInputStream in;
    BufferedReader br;
    boolean eof = false;
    try {
        ssc = ServerSocketChannel.open();
        ssc.socket().bind(new InetSocketAddress(hostname, port));
        ssc.configureBlocking(false);
        fstream = new FileInputStream("input_vector.txt");
        in = new DataInputStream(fstream);
        br = new BufferedReader(new InputStreamReader(in));

        try {
            InitClients.barrier.await();
        }
        catch (Exception e) {
            System.out.println(e);
        }

        while (true && (eof == false)) {
            sc = ssc.accept();

            if (sc == null) {
                if ((strLine = br.readLine()) != null) {
                    int result = parseAction(strLine);
                    if (result >= 0) {
                        //System.out.println("[" + (clientNumber + 1)
                        //+ "] Send a message to " + result + ".");
                        try {
                            SocketChannel client = SocketChannel.open();
                            client.configureBlocking(true);
                            client.connect(
                                    new InetSocketAddress("localhost",
                                    parsePort(result)));
                            //ByteBuffer buf = ByteBuffer.allocateDirect(32);
                            //buf.put((byte)0xFF);
                            //buf.flip();
                            //vectorClock[clientNumber] += 1;
                            //int numBytesWritten = client.write(buf);
                            String obj = Integer.toString(clientNumber+1);
                            ObjectOutputStream oos = new 
                                    ObjectOutputStream(
                                    client.socket().getOutputStream());
                            oos.writeObject(obj);
                            oos.close();
                        }
                        catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                else {
                    eof = true;
                }
            }
            else {
                ObjectInputStream ois = new 
                        ObjectInputStream(sc.socket().getInputStream());
                String clientNumberString = (String)ois.readObject();
                System.out.println("At {Client[" + (clientNumber + 1)
                        + "]}Incoming connection from: "
                        + sc.socket().getRemoteSocketAddress()
                        + " from {Client[" + clientNumberString + "]}");
                sc.close();
            }
            try {
                InitClients.barrier.await();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    printVector();
}

private void printVector() {
    System.out.print("{Client[" + (clientNumber + 1) + "]}{");
    for (int i = 0; i < vectorClock.length; i++) {
        System.out.print(vectorClock[i] + "\t");
    }
    System.out.println("}");
}

为了
澄清,这里是使用的文件格式。配置包含客户端使用的主机名和端口,它们是线程,输入文件的行表示“此客户端向该客户端发送消息”或“此客户端将其逻辑时钟增加某个常数值”。

1 M 2 (M 表示发送消息)
2 M 3
3 M 4
2 L 7 (L 表示递增时钟)
2 M 1
...
127.0.0.1 9000
127.0.0.1 9001
127.0.0.1 9002
127.0.0.1 9003
...

4

1 回答 1

0

我将查看与您何时期望传入套接字连接相关的逻辑。从您的问题来看,您似乎期望一定数量的传入套接字连接(可能是每条传出消息之后的传入连接?)。由于您在传入套接字上使用非阻塞 I/O,因此您的 while 语句总是可能在传入套接字建立之前循环。结果,线程将能够继续并从文件中读取下一行,而无需接收连接。由于一旦到达文件末尾就到达了结束状态,因此您可能会错过传入的套接字连接。

我会添加一些简单的打印输出,当您从文件中读取、发送消息和接收传入连接时显示这些输出。这应该会很快告诉您某个特定线程是否缺少预期的传入连接。如果事实证明问题是由于非阻塞 I/O 造成的,那么您可能需要在预期传入套接字时禁用非阻塞 I/O,或者实现一个控制来跟踪预期传入套接字的数量并一直持续到实现该目标。

希望这可以帮助。

于 2011-02-11T13:22:35.170 回答