与UDP广播的客户端 - 服务器连接

时间:2016-04-09 19:15:01

标签: java udp

我必须实现一个定位服务"在局域网内。 服务器:我们必须实现一个协议,它允许我们处理不同服务的请求。它还应该支持多个服务器实例的可能性,这也可能有不同的服务。

  

即:我有4项服务:( Add,Sub,Mul和Div)

     

我想创建3台服务器:

     
      
  • Server1提供Add and Mul
  •   
  • Server2提供Mul和Div
  •   
  • Server3提供Sub
  •   

现在我应该意识到CLient方面,它想要使用这些服务之一。客户端的请求服务于哪个服务器并不重要。

  

即。客户想要做" Mul 13 7" 然后一个DatagramPacket应该   由客户发送并由服务器发送。然后Server1或Server2应该   计算 13 * 7 并将结果返回给客户。

所有这些连接都应该在没有硬编码端口和IP的情况下完成。我不知道如何处理多个服务器实例并在没有端口的情况下连接它们。我们得到了一个提示,我们应该使用 DatagramSockets。

这里我有一个程序,适用于1服务器:

Serverside:

package UDPBroadcast;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;


public class ServiceAnnouncer {

    private String[] serviceTable; 
    private DatagramSocket socket;
    private int port;
    private final byte[] buffer = new byte[12];

    /**
     * ** CONSTRUCTOR **
     * 
     * Sets the new port for datagram socket.
     * 
     * @param port Integer with a port number.
     */

    public ServiceAnnouncer( String[] tbl, int port) {
        this.serviceTable = tbl;
        this.port = port;
    }

    /**
     * Server listening for package.
     */
    public void start() {
        System.out.println("Server is started!");
        System.out.println("Services" );
        for( String s : serviceTable )
            System.out.println(s);
        try {
            /*
             * Opens the UDP port, throws SocketException if it is already in use
             * or it is not able to open.
             */
            socket = new DatagramSocket(port);
            /*
             * Handles a multiple number of requests.
             */
            while (true) {
                /*
                 *  Waiting for a package from client/clients. 
                 */
                final DatagramPacket packet = new DatagramPacket(buffer,
                        buffer.length);
                /*
                 * Receives the packet of the datagram socket.
                 */
                socket.receive(packet);
                /*
                 * Read the received data.
                 */
                final String data = new String(packet.getData()).trim();
                /*
                 * Answer only if the message contains Ping.
                 */
                String[] pack = data.split(" ");
                if ( checkService( pack[0], serviceTable )) {
                    System.out.println("Ping sent from client : "
                            + packet.getAddress().getHostAddress() + ":"
                            + packet.getPort());
                    int result = 0;
                    if(pack.length == 3 )
                         result = calc( pack[0], Integer.valueOf( pack[1]), Integer.valueOf( pack[2]));
                    else
                        result = calc( pack[0], Integer.valueOf( pack[1] ), 0 );


                    /*
                     * Send a response to the ServiceLocator.
                     */
                    final DatagramPacket response = new DatagramPacket(
                            String.valueOf( result ).getBytes(),
                            String.valueOf( result ).length(),
                            packet.getAddress(), packet.getPort());
                    socket.send(response);
                } else {
                    System.out.println("Invalid message: " + data);
                }

            }
        } catch (final SocketException e) {
            System.out.println("Port is already in use!");
            e.printStackTrace();
        } catch (final IOException e) {
            System.out.println("Communication error!");
            e.printStackTrace();
        } finally {
            socket.close();
        }
    }

    public static boolean checkService( String serv, String[] tbl )
    {
        for( String s : tbl )
        {
            if( s.equalsIgnoreCase( serv ) )
                return true;
        }
        return false;
    }

    /** Calculates [param1] [op] [param2], if op [+,-,*] or [op] [param1] if op[lucas]
     * 
     *@param op the operation
     *@param param1 parameter1
     *@param param2 parameter2
     *
     *@return returns the result
     */
    private static int calc( String op , int param1, int param2 ) 
    {
        int result = 0;
        switch ( op ) 
        {
            case "+": 
            {
                result = param1 + param2;
                break;
            }

            case "-": 
            {
                result = param1 - param2;
                break;
            }

            case "*": 
            {
                result = param1 * param2;
                break;
            }

            case "lucas": 
            {
                if ( param1 == 0 ) 
                    result = 2;

                else if ( param1 == 1 )
                    result = 1;

                else
                {
                    int first = 2;
                    int second = 1;
                    for ( int i = 0; i < param1-1; i++ ) 
                    {
                        result = first + second;
                        first = second;
                        second = result;
                    }
                }
                break;
            }   
            default:
                break;
        }
        return result;
    }

    /**
     * Main method to start the server.
     * 
     * @param args Not The supported services.
     */
    public static void main(final String[] args) {
        final ServiceAnnouncer server = new ServiceAnnouncer( args, 12345);
        server.start();
    }
}

CLientside:

package UDPBroadcast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;


public class ServiceLocator 
{
    private String service;
    private int port;
    private int timeout;

    /**
     * ** CONSTRUCTOR **
     * 
     * @param port
     * @param timeout
     */
    public ServiceLocator( String serv, int port, int timeout) {
        this.service = serv;
        this.port = port;
        this.timeout = timeout;
    }

    /**
     * Client locating server and sending package.
     * 
     * @return InetAddress of Service
     * @throws UnknownHostException
     *             the Service could not be found.
     */
    public DatagramPacket locate() throws UnknownHostException {
        try {
            System.out.println("Client is started!");
            BufferedReader inFromStdIn = new BufferedReader( new InputStreamReader( System.in ) );
            /*
             * Create a packet to the broadcast Address 255.255.255.255
             * with the content "Ping".
             */
            String read = inFromStdIn.readLine();
            byte[] ba = read.getBytes();
            DatagramSocket socket = new DatagramSocket();
            byte adr = (byte) 255;
            byte[] address = { adr, adr, adr, adr };
            InetAddress internetAdress = InetAddress.getByAddress(address);
            DatagramPacket packet = new DatagramPacket(ba, ba.length, internetAdress, port);
            /* Send Ping request. */
            socket.send(packet);
            /* Wait for response 5000 milliseconds. */
            socket.setSoTimeout(timeout);
            socket.receive(packet);

            /*
             * Return the address.
             */
            return packet;
        } catch (final IOException e) {
            /* If there is an error throw that the host isn't found. */
            throw new UnknownHostException();
        }
    }

    public static void main(final String[] args) {
        ServiceLocator client = new ServiceLocator( "Addition",12345, 5000);
        try {
            DatagramPacket address = client.locate();
            byte[] ss = address.getData();
            String str = new String( ss, StandardCharsets.UTF_8 );
            System.out.println("Service is using : " + str);
        } catch (final UnknownHostException e) {
            System.out.println("Service cannot be found!");
        }
    }
}

此代码工作正常。但是现在我想创建多个服务器(当然必须有不同的端口)并正确处理它们。有人可以解释一下我是如何实现的吗?

谢谢

0 个答案:

没有答案