6

http://i.stack.imgur.com/97ERA.png

  1. 我有 3 个节点 A、B 和 C 以及它们各自的端口号。
  2. 我正在尝试编写一个接受3 个参数的 java 程序:它的节点名称和它的2 个相邻节点的端口并向它们广播一个字符串"Hello I'm A"(因此 A 将广播到 B 和 C)。它将每 3 秒执行一次。
  3. 该程序将在 3 个单独的实例中运行。
  4. 收到字符串后,它将打印它从哪个节点接收到它"Received string"(例如端口 B)。

我很难实现这一点,multicasting不过我听说过一些叫做 UDP 的东西。这是我到目前为止的工作,我做错了什么?

class UDP {
    public static void main(String[] args) throws Exception {
        String nodeName = args[0];
        int neighbourPort1 = Integer.valueOf(args[1]);
        int neighbourPort2 = Integer.valueOf(args[2]);

        while(true) {
            Thread.sleep(3000); //every 3 seconds
            //Continously broadcast and listen to neighbour1
            DatagramSocket socket1 = null;
            try {
                //CREATE SOCKET TO NEIGHBOUR1
                InetAddress host = InetAddress.getByName("localhost");
                socket1 = new DatagramSocket();
                socket1.connect(host, neighbour1);

                //CREATE DATAGRAMS FOR SENDING
                String message = "Hello I'm " + nodeName;
                byte[] sendData = message.getBytes();
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, host, port);
                socket1.send(sendPacket);

                //CREATE DATAGRAMS FOR RECEIVING
                byte[] receiveData = new byte[100]; //is there a way to determine the needed space?
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                socket1.receive(receivePacket);
                System.out.println("Received string");

            } catch(Exception e) { }
            //Do the same for neighbour2, code is basically identical except for variables
            DatagramSocket socket2 = null;
            try {
                //CREATE SOCKET TO NEIGHBOUR2
                InetAddress host = InetAddress.getByName("localhost");
                socket2 = new DatagramSocket();
                socket2.connect(host, neighbour2);

                //FOR SENDING DATAGRAMS
                String message = "Hello I'm " + nodeName;
                byte[] sendData = message.getBytes();
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, host, port);
                socket2.send(sendPacket);

                //FOR RECEIVING DATAGRAMS
                byte[] receiveData = new byte[100]; //is there a way to determine the needed space?
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                socket2.receive(receivePacket);
                System.out.println("Received string");

            } catch(Exception e) { }
        }

    }
}

我知道我已经接近解决方案了。我能够正常广播,但让我受益的是不断倾听的部分。

4

2 回答 2

3

我认为最好使用单独的线程来监听您自己端口上的数据。

  • A向B发送数据并阻塞,直到它从B获得数据包。
  • B向C发送数据并阻塞,直到它从C获得数据包。
  • C向A发送数据并阻塞,直到它从A获得数据包。

每个节点都在等待对方。只需发送数据包并等待 3 秒。另一个线程将只听

public class UDP {

    public static void main(String[] args) throws Exception {
        final String nodeName = args[0];
        final int ownPort = Integer.valueOf(args[1]);
        final int neighbourPort1 = Integer.valueOf(args[2]);
        final int neighbourPort2 = Integer.valueOf(args[3]);


        // Don't create a new socket every time
        DatagramSocket neighbour1 = new DatagramSocket();
        DatagramSocket neighbour2 = new DatagramSocket();

        neighbour1.connect(InetAddress.getLocalHost(), neighbourPort1);
        neighbour2.connect(InetAddress.getLocalHost(), neighbourPort2);

        // You have to LISTEN
        new Thread() {
            @Override
            public void run() {
                try {
                    DatagramSocket socket = new DatagramSocket(ownPort);

                    byte[] buffer = new byte[socket.getReceiveBufferSize()];
                    DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

                    while (true) {
                        // Blocks until it gets a packet
                        socket.receive(packet);

                        System.out.println("Received string");
                    }

                    // socket.close();
                } catch (final Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();

        while (true) {
            Thread.sleep(3000);

            sendPacket(neighbour1, nodeName);
            sendPacket(neighbour2, nodeName);
        }

        // If you're not using an infinite loop:
        // neighbour1.close();
        // neighbour2.close();
    }

    private static void sendPacket(DatagramSocket to, String from) throws Exception {
        String message = "Hello I'm " + from;
        byte[] data = message.getBytes();

        DatagramPacket packet = new DatagramPacket(data, data.length);
        to.send(packet);
    }

}
于 2012-10-17T14:52:02.757 回答
1

这是一个简单的服务器框架,具有两个线程,一个写入和一个读取,将您的网络代码放置在正确的位置。

package testing;

import java.util.Scanner;

public class ThreadTest {
public class MyListenerThread extends Thread {

@Override
public void run() {
    /*
     * Open Datagram ...
     */
    while (true) {
    /*
     * Read data ...
     */
    Scanner scanner = new Scanner(System.in);
    System.out.println("read: " + scanner.next());
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    }
}

}

public class MySenderThread extends Thread {
@Override
public void run() {
    /*
     * Open Multicast ...
     */
    while (true) {
    /*
     * Send ...
     */
    System.out.println("Send ...");
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    }
}

}

public void start() {
MyListenerThread listener = new MyListenerThread();
MySenderThread sender = new MySenderThread();

listener.start();
sender.start();
}

public static void main(String[] args) {
ThreadTest server = new ThreadTest();
server.start();
}

}
于 2012-10-17T14:48:31.980 回答