2

我是一个初学者,我为此学习了教程,但仍然不知道如何实现这一点。

我有两个 while 循环,一个在 main() 方法中,一个在 send() 方法中,都需要同时执行,我该怎么做。

public static void main(String[] args) throws Exception
{   
    socket = new DatagramSocket(13373); // 69 Reserved for TFTP

    // Listen for incoming packets
    while(true) {
        // Do things
    }
}

private static void sendDATA() {
    while(true) {
        // Do things
    }
}

sendDATA 中的 while 循环通过从文件中读取 512 个字节然后将它们发送到客户端类来工作。虽然 main 方法中的循环从客户端接收数据包并更新变量,如果变量为真,则 sendDATA 读取下一个 512 字节并发送它们等等,但我不能在两个线程中工作。

我已经用一个while循环完成了这个并且程序可以正常工作,它可以传输除最后一个之外的所有数据包。客户端永远不会得到最后一个数据包。

服务器:

    public static void main(String[] args) throws Exception
{   
    socket = new DatagramSocket(13373); // 69 Reserved for TFTP

    // Listen for incoming packets
    while(true) {
        DatagramPacket packet = new DatagramPacket(incoming, incoming.length);
        socket.receive(packet);

        clientip = packet.getAddress().toString().replace("/", "");
        clientport = packet.getPort();

        System.out.println(clientport);

        if(incoming[0] == 1 || incoming[0] == 2) {
            handleRequest(incoming);
        } 

    }
}

// sends DATA opcode = 3 : | opcode | block # | data |
private static void sendDATA() {

    try {
        ByteBuffer sDATA = ByteBuffer.allocate(514);

        byte[] tmp = new byte[512];
        DatagramPacket data = new DatagramPacket(sDATA.array(), sDATA.array().length, InetAddress.getByName(clientip), clientport);
        InputStream fis = new FileInputStream(new File(FILE));

        int a;
        int block = 1; 

        while((a = fis.read(tmp,0,512)) != -1)
        {
            data.setLength(a);
            sDATA.put((byte)3);
            sDATA.put((byte)block);
            System.out.println(sDATA.array().length);
            sDATA.put(tmp);
            System.out.println(tmp.length);
            socket.send(data); 

            socket.setSoTimeout(60000);

            while(true) {
                DatagramPacket getack = new DatagramPacket(incoming, incoming.length);
                try {
                    socket.receive(getack);
                    if(incoming[0] == 4 && incoming[1] == block) {  
                        break;
                    } else if(incoming[0] == 4 && incoming[1] == block && tmp.length < 511) {
                        fis.close();
                        break;
                    }
                } catch (SocketTimeoutException e) {
                   socket.send(data);
                   continue;
                }

            }
            block++;
        }       
    } catch (Exception e) {
        e.printStackTrace();
    }

}

客户:

public static void main(String[] args) throws Exception
{
    clientSocket = new DatagramSocket(8571);

    // WRQ || RRQ
    Scanner input = new Scanner(System.in);
    int opcode = input.nextInt(); input.close();

    // Pripravi paketek
    outgoing = makeRequestPacket(opcode,"filename.txt","US-ASCII");

    // Odposlje pakete
    sendPacket(outgoing);

    // Streznik vrne ACK - opcode 4 ali ERROR - opcode 5
    // Pri ACK zacnemo posiljat DATA opcode 3 drugace prekinemo povezavo ob ERROR - opcode 5
    while(true) {
        DatagramPacket receiveResponse =  new DatagramPacket(incoming, incoming.length);
        clientSocket.receive(receiveResponse);

        // opcode 5 - ERROR
        if(incoming[0] == 5) {
            getError(incoming);
        } 
        else if(incoming[0] == 4 && incoming[1] == 0) { // opcode 4 - Prvi ACK
            System.out.print("opcode: (" + incoming[0] +") ACK received operation confirmed.");
            continue;
        } 
        else if(incoming[0] == 3) {
            System.out.println("Ah got a data packet.");
            File initfile = new File("filename2.txt");
            if(!initfile.exists()) {
                initfile.createNewFile();
            } 

            int block;
            FileOutputStream fio = new FileOutputStream(initfile);

            if(incoming.length > 511) {
                block = incoming[1];
                System.out.println("Will start to write.");

                for(int i = 2; i < incoming.length; i++) {
                    fio.write(incoming[i]);
                }
                ByteBuffer recack = ByteBuffer.allocate(514);
                recack.put((byte)4);
                recack.put((byte)block);
                System.out.println("If i came here and nothing happened something went horribly wrong.");

                DatagramPacket replyACK = new DatagramPacket(recack.array(), recack.array().length, InetAddress.getByName("localhost"),13373);
                clientSocket.send(replyACK);
            } else if (incoming.length < 511) {
                System.out.println("Last chunk.");
                block = incoming[1];
                for(int j = 2; j < incoming.length; j++) {
                    if(incoming[j] != 0) {
                        fio.write(incoming[j]);
                    } else {
                        break;
                    }
                }
                ByteBuffer recack = ByteBuffer.allocate(514);
                recack.put((byte)4);
                recack.put((byte)block);


                DatagramPacket replyACK = new DatagramPacket(recack.array(), recack.array().length, InetAddress.getByName("localhost"),13373);
                clientSocket.send(replyACK);
                fio.close();
                clientSocket.close();
                break;
            }
            continue;

        }
    }


}
4

2 回答 2

2

您必须使用阻塞通道来同步进程之间的通信:

SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(true);

更多信息:http ://docs.oracle.com/javase/1.4.2/docs/api/java/nio/channels/SocketChannel.html

此外,套接字被设计为在进程之间发送数据,如果不是这种情况,您的方法是错误的,您应该更改您的设计,即当(或每次)数据准备好时在新线程中调用每个循环(每个线程将处理它的数据然后死掉),或者如果您不需要并发执行,则只需在一个循环内顺序执行两个指令块。程序的状态图可以帮助您确定最佳解决方案。

于 2012-09-11T08:45:13.853 回答
0

所以我一直在寻找的是一种简单的“粗略”方式,可以同时运行同一类的两个方法,用于实例化两个独立循环。无论如何这里是代码:

    class MyClass extends Thread {

public void run() {     // start new thread
    otherMethod();      // will calls another method
}
void otherMethod() {
     ....  executed in another Thread
}

public static void main(String[] args) {
   MyClass mc = new MyClass();
   mc.start();                 // start other Thread
   ... continue in main() with actual thread
   ...
}
}
于 2012-09-11T17:28:29.320 回答