문제

I am 정에서 네트워크 아키텍처에 1 곳을 구현해야하고 거리 벡터 라우팅에서는 각 노드입니다.

에서는 각 노드,내가 스레드는 수신하는 수신 DatagramPackets 을 포함하는 경로 정보에서 이웃의 노드 만에서 특정한 포트입니다.할 때는 데이터그램에 도착,스레드 프로세스는 데이터그램이며,업데이트가 있는 경우에는 그 내부는 라우팅 테이블,그것은 전송의 라우팅 정보를 모두 이용하실 수 있습니다.

내가 노력하고 그것을 할 수 있습니다.

문제 내가 직면하는 데이터그램에 도착해야를 처리합니다.면 그 시간 동안 다른 어떤 데이터그램에 도착,그것이 떨어졌으로 스레드가 현재 정보를 처리하는 단계를 포함한다.는 의미입니다.

할 수 있는 어떤 사람이 나에게 도움이 될 이?

내가 사용하는 일반적인 방법에서 읽은 소켓에서 java.

DatagramSocket socket = new DatagramSocket(4445, InetAddress.getByName("127.0.0.1"));
while (true) {
    try {
        byte[] buf = new byte[2000];

        // receive request
        DatagramPacket recvRequest = new DatagramPacket(buf, buf.length);

        socket.receive(recvRequest);

        //Some process of data in datagram

    } catch (IOException e) {
        e.printStackTrace();
    }
}
도움이 되었습니까?

해결책

Datagramsocket Socket = 새로운 Datagramsocket (4445, inetAddress.getByName ( "127.0.0.1")); while (true) {try {// final .. final .. final byte [] buf = new byte [2000];

    // receive request
    DatagramPacket recvRequest = new DatagramPacket(buf, buf.length);

    socket.receive(recvRequest);

    //Some process of data in datagram
    (new Thread(new Runnable() {
        public void run () {
            // do stuff with data in buf
            ...
        }
    })).start();

} catch (IOException e) {
    e.printStackTrace();
}

}

다른 팁

할 수 있는 프로세스 수신 데이터그램에서 스레드,그래서 당신의 스레드 소켓 리스너를 계속 받을 수 있습 새로운 데이터그램.

이것은 내가 제출 한 마지막 프로젝트입니다. 부적절한 문서화와 Java의 잘못된 사용법이있을 수 있습니다. 이 프로젝트는 다른 IP 주소와 동일한 포트 번호를 사용하는 대신 로컬 시스템에서 실행되면 다른 방식으로 수행하고 있습니다.

NetworkBoot.java는 각 라우터에 초기 이웃 세부 사항을 제공합니다.

감사합니다 -Sunny Jain

enter code here

/ * * 파일 이름 : router.java * 공개 클래스 이름 : 라우터 * */

// ~ --- JDK 수입 ------------------------------------------- ------------------

import java.io.ioexception;

import java.net.datagrampacket;

import java.net.datagramsocket;

import java.net.inetAddress;

java.util.hashmap import;

import java.util.iterator;

import java.util.set;

import java.util.concurrent.linkedBlockingqueue;

import javax.swing.swingutilities;

/** * * NA1 프로젝트 2 2009 학기 * @Author Sunny Jain * * */

공개 클래스 라우터 확장 스레드 {

/**
 * HashMap containing list of neighbors and cost to reach them.
 */
private HashMap<Integer, Integer> hmapDirectNeighbours = new HashMap<Integer, Integer>(61);
/**
 * HashMap containing list of destination as key and routing info to them as value.
 * Routing info contains RouteDetail object.
 * @see RouteDetail
 */
private HashMap<Integer, RouteDetail> hmapRoutes = new HashMap<Integer, RouteDetail>();
/**
 * DatagramSocket
 */
private DatagramSocket dSoc;
/**
 * DatagramPacket
 */
private DatagramPacket dpackReceive,  dpackSend;
/**
 * Inetaddress of system on which runs this algorithm.
 */
private InetAddress localAddress;
/**
 * port to listen at for incoming route info from neighbors.
 */
int port;
private LinkedBlockingQueue<DatagramPacket> lbq = new LinkedBlockingQueue<DatagramPacket>();

/**
 * Made constructor private to force initialization by specifying port
 * compulsory.
 */
private Router() {
}

/**
 * Constuctor taking port number as parameter and creates a datagramSocket
 * to listen for incoming DatagramPacket on that socket.
 * @param port
 */
public Router(int port) {
    try {
        this.port = port;
        localAddress = InetAddress.getByName("127.0.0.1");
        dSoc = new DatagramSocket(port, localAddress);
    } catch (Exception ex) {
        System.out.println("Error while creating socket : " + ex.getMessage());
    }
    this.start();

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            while (true) {
                try {
                    received_Route_Info(lbq.take());
                } catch (InterruptedException ex) {
                    System.out.println("Error while reading elements from datagram queue");
                }}}});
}

public void setRouterBootInfo(String strNeighboursInfo) {
    String[] strNeighbouringNodes = strNeighboursInfo.split(";");

   for (int i = 0; i < strNeighbouringNodes.length; i++) {

        String[] strNodeIpAndPort = strNeighbouringNodes[i].split(":");

        hmapDirectNeighbours.put(Integer.valueOf(strNodeIpAndPort[0]), Integer.valueOf(strNodeIpAndPort[1]));
        hmapRoutes.put(Integer.valueOf(strNodeIpAndPort[0]), new RouteDetail(null, Integer.valueOf(strNodeIpAndPort[1])));
    }
    propagateChanges();
// entry in Route table....No need for infinity as we creat entry when a node is reachable.
}

@Override
public void run() {
    while (true) {
        try {
            byte[] buf = new byte[250];
            // receive request
            dpackReceive = new DatagramPacket(buf, buf.length);
            dSoc.receive(dpackReceive);
            lbq.put(dpackReceive);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
            dSoc.close();
        } catch (IOException e) {
            e.printStackTrace();
            dSoc.close();
        }
    }


}

/**
 * This method is called for each DatagramPacket received containing new
 * routing information.
 *
 * This method checks whether this packet came from neighboring node
 * (routers) only. If true it applies Distance vector algorithm on data
 * present in datagram packet and due to this information if their is any
 * change in local routing information that it displays current local
 * updated routing information and also sends this updated information to
 * other neighbours only.
 *
 * @param dataPckt
 * @see  #validate_Is_Packet_From_Neighbor(java.net.DatagramPacket)
 * @see #apply_Routing_Algorithm(java.net.DatagramPacket, java.util.HashMap)
 * @see #print_route_info()
 * @see #send_Updates_To_Neighbors(routesInfo)
 */
private void received_Route_Info(DatagramPacket dataPckt) {
    if (dataPckt.getPort() == 4000) {
        setRouterBootInfo(getStringFromBytes(dataPckt));
    } else if (validate_Is_Packet_From_Neighbor(dataPckt)) {
        if (apply_Routing_Algorithm(dataPckt, create_HashMap_Routes(getStringFromBytes(dataPckt)))) {

            // if their is change in routing information.
            propagateChanges();
        }
    }
}

/**
 * Validates whether the Datagram packet received is from the neighbors only.
 * @param datagrampckt DatagramPacket comtaining routing information.
 * @return true if datagrampckt is from neighbors only otherwise false.
 */
private boolean validate_Is_Packet_From_Neighbor(DatagramPacket datagrampckt) {
    return hmapDirectNeighbours.containsKey(Integer.valueOf(datagrampckt.getPort()));
}

/**
 * Returns byte representaion of data contained in DatagramPacket pkt.
 * @param pkt DatagramPacket
 * @return byte representation of data contained in pkt
 */
private String getStringFromBytes(DatagramPacket pkt) {
    String strData = new String(pkt.getData());
    return strData.substring(0, strData.lastIndexOf(';'));
}

/**
 * Applies Distance Vector algorithm using newly received routing information
 * and information presently with this node (Router).
 * @param datagrampckt DatagramPacket containing routing information.
 * @param newRoutes HashMap of routes new information received with
 * destination as key and cost to that destination as value.
 */
private boolean apply_Routing_Algorithm(DatagramPacket dataPckt, HashMap<Integer, Integer> newRoutes) {
    boolean updated = false;
    Integer pktSourse = Integer.valueOf(dataPckt.getPort());

    // Get a set of the routes
    Set<Integer> set = newRoutes.keySet();

    // Get an iterator
    Iterator<Integer> iterator = set.iterator();

    // Display elements.
    while (iterator.hasNext()) {
        Integer key = iterator.next();
        Integer nextHopCost = hmapRoutes.get(pktSourse).getPathCost();
        int optionalCost = newRoutes.get(key) + (nextHopCost == null ? 0 : nextHopCost);
        if (hmapRoutes.containsKey(key)) {
            RouteDetail routeDetail = hmapRoutes.get(key);

            if (routeDetail.getPathCost().compareTo(optionalCost) > 0) {
                routeDetail.setNextHop(pktSourse);
                routeDetail.setPathCost(optionalCost);
                hmapRoutes.put(key, routeDetail);
                updated = true;

            // try to verify above statement
            }
        } else {
            if (!key.equals(port)) {
                RouteDetail newRouteDetail = new RouteDetail(pktSourse, optionalCost);
                hmapRoutes.put(key, newRouteDetail);
                updated = true;
            }
        }
    }

    return updated;
}

/**
 * When internal routing information is chaged, send this information to
 * other neighbors.
 * @param routesInfo byte representaion of routing information.
 */
private void send_Updates_To_Neighbors(byte[] routesInfo) {

    // Get a set of the routes
    Set<Integer> set = hmapDirectNeighbours.keySet();

    // Get an iterator
    Iterator<Integer> iterator = set.iterator();

    // Display elements.
    while (iterator.hasNext()) {
        dpackSend = new DatagramPacket(routesInfo, routesInfo.length, localAddress, iterator.next().intValue());

        try {
            dSoc.send(dpackSend);
        } catch (IOException ex) {
            System.out.println("Error while sending route updates : " + ex.getMessage());
        }
    }
}

/**
 * Parses routeInfo to creat an HashMap based on this informationin the
 * format as HashMap of <<Integer:Destination>,<Integer: Cost to this destination>>
 * @param routeInfo contains routing information as String in the syntax
 * of {<Destination>:<Cost to destination>;}
 * @return Hashmap<<Integer:Destination>,<Integer: Cost to this destination>>
 */
private HashMap<Integer, Integer> create_HashMap_Routes(String routeInfo) {
    HashMap<Integer, Integer> routes = new HashMap<Integer, Integer>();
    String[] straRoute = routeInfo.split(";");

    for (int i = 0; i < straRoute.length; i++) {
        String[] straDestAndCost = straRoute[i].split(":");

        routes.put(Integer.parseInt(straDestAndCost[0]), Integer.parseInt(straDestAndCost[1]));
    }

    return routes;
}

/**
 * Converts current routing information stored as HashMap to String
 * presentation in format as {<Destination>:<Cost to destination>;}
 *
 * @return String representaion of routing information.
 * @see #hmapRoutes.
 */
private String create_String_Of_Routes() {
    StringBuilder strB = new StringBuilder();

    // Get a set of the routes
    Set<Integer> set = hmapRoutes.keySet();

    // Get an iterator
    Iterator<Integer> iterator = set.iterator();

    // Display elements.
    while (iterator.hasNext()) {
        Integer destination = iterator.next();

        strB.append(destination);
        strB.append(":");
        strB.append(hmapRoutes.get(destination).getPathCost());
        strB.append(";");
    }

    return strB.toString();
}

/**
 * Prints the current routing information stored in <code>hmapRoutes</code>
 * to default output stream of this program.
 * @see #hmapRoutes.
 */
public void print_route_info() {
    RouteDetail route;
    StringBuilder builder;

    // PRINT THE CURRENT ROUTING INFO AT THIS NODE
    System.out.println("");
    System.out.println("    TABLE AT NODE WITH PORT  : " + port);
    System.out.println("--------------------------------------------------------------------------------");
    System.out.println("\t\tTo  \t|\t Via\t|\tCost\t\t");
    System.out.println("--------------------------------------------------------------------------------");

    // Get a set of the routes
    Set<Integer> set = hmapRoutes.keySet();

    // Get an iterator
    Iterator<Integer> iterator = set.iterator();

    // Display elements.
    while (iterator.hasNext()) {
        Integer key = iterator.next();

        route = hmapRoutes.get(key);
        builder = new StringBuilder();
        builder.append("\t\t" + key.intValue());
        builder.append("\t|\t" + (route.getNextHop() == null ? "   -" : route.getNextHop()));
        builder.append("\t|\t" + route.getPathCost() + "\t\t");
        System.out.println(builder.toString());
    }
}

/**
 * This class provides details for each destination.
 * It provides detail of cost that will be incurred to reach that
 * destination and next router on that path.
 */

개인 클래스 라우 티 테일 {

    Integer nextHop;
    Integer pathCost;

    public RouteDetail(Integer nextHop, Integer pathCost) {
        this.nextHop = nextHop;
        this.pathCost = pathCost;
    }

    public Integer getNextHop() {
        return nextHop;
    }

    public void setNextHop(Integer nextHop) {
        this.nextHop = nextHop;
    }

    public Integer getPathCost() {
        return pathCost;
    }

    public void setPathCost(Integer pathCost) {
        this.pathCost = pathCost;
    }
}

private void propagateChanges() {
    print_route_info();
    send_Updates_To_Neighbors(create_String_Of_Routes().getBytes());
}

public static void main(String[] args) {
    new Router(Integer.parseInt(args[0]));
}

}

/ * * 파일 이름 : NetworkBoot.java * 공개 클래스 이름 : NetworkBoot * */

import java.io.ioexception;

import java.net.datagrampacket;

import java.net.datagramsocket;

import java.net.inetAddress;

/** * * NA1 프로젝트 2 2009 학기 * @Author Sunny Jain * * */

공개 클래스 네트워크 부츠 {

public static void main(String[] args) {
    try {
        DatagramSocket dSoc = new DatagramSocket(4000, InetAddress.getByName("127.0.0.1"));
        String[] sendD = {"4006:3;4007:5;4009:2;", "4005:3;4007:3;4008:6;", "4005:5;4006:3;", "4009:2;4006:6;", "4008:2;4005:2;"};
        for (int i = 0, port = 4005; i < 5; i++) {
            dSoc.send(new DatagramPacket(sendD[i].getBytes(), sendD[i].length(), InetAddress.getByName("127.0.0.1"), port++));
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

}

나는에서 Java,하지만,당신은 할 수 있습니다(또는 해야한다)통과 하나 이상의 동시 데이터그램이 버퍼는 소켓(또 여러 각 스레드를 호출하여 synchrnonous 받는 방법,또는 바람직 하나의 스레드를 호출하는 asynchrnonous 받는 방법을 두 번 이상).

의 이점을 통과 동시에 여러 개의 버퍼에 데이터그램 소켓은 분명하다:즉소켓이 여전히 버퍼(을 받는 다음 데이터그램)는 동안에도 그것은 이미 채워진 하나의 버퍼(이전 데이터그램)및 전달되는 버퍼니다.

를 요청할 수 있습니다,"어떤 순서가 버퍼를 다시 전달할까?"하고 대답을 하는 것은,"그것은 중요하면 안된다." 는 경우에는 순서 당신은 프로세스는 데이터그램은 중요한 다음 데이터그램 자체가 포함되어야 합 순서 번호(있기 때문에 데이터그램을 얻을 수 있습의 순서로 그들을 통해 라우팅,네트워크는지 여부를 당신이 통과 동시에 여러 개의 로컬 소켓으로 결과의 가능성에"동시에"받 전달되는 것 당신을 다시 순서).

UDP는 잃어버린 전송이라는 것을 기억하는 것이 좋습니다. 패킷 손실을 최소화하는 것은 좋은 생각입니다. 모든 패킷을 얻지 못할 것이라고 생각하지 않아야합니다 (또는 패킷이 보낸 순서대로 도착할 것입니다)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top