Вопрос

I am using connectionless sockets to create a Remote String Processor. The user is to enter two terms and an integer, all separated by spaces. This input becomes two strings and an integer. If an invalid integer is entered, an error message displays and the program ends. If a valid integer is entered, a certain method is performed on the two strings. After the method is performed, I would like to save the result to a variable along with words I add (see case 1) and send it to the user. This is the sender-receiver part of the application. There is a receiver-sender part that I did not post. I have not finished cases 2-5. Once I find out how to do case 1, maybe I will have been provided with enough direction to complete those on my own.

import java.net.*;
import java.io.*;

class datagramSR{
    public static void main(String[ ] args){
        try{
        InetAddress receiverHost = InetAddress.getByName(args[0]);
        int receiverPort = Integer.parseInt(args[1]);

        System.println("Input is accepted in the form of term1 term2 choice\n");
        System.println("To lexicographically compare terms, choose 1");
        System.println("To append term2 to term1, choose 2");
        System.println("To determine if term1 ends with term2, choose 3");
        System.println("To determine if term1 starts with term2, choose 4");
        System.println("To return the index of the first occurrence of term2 in term1, choose 5");
        DatagramSocket mySocket = new DatagramSocket(message);

        //tokenize input into 2 strings
        StringTokenizer stack = new StringTokenizer();

        String string1 = stack.nextToken();
        String string2 = stack.nextToken();
        //cases for method codes
        int code = Integer.parseInt(stack.nextToken());
        if( code==1 || code==2 || code==3 || code==4 || code==5) {
            switch(code) {
            case 1: string1.compareTo( string2 );
                    if(>0) { message = string1" comes after "string2" lexicographically";
                    }
                    else if(<0) { message = string1" comes before "string2" lexicographically";
                    }
                    else if(0) { message = Term1 and term2 are the same;
                    }
                    byte[] sendBuffer = message.getBytes( );
                    DatagramPacket packet = new DatagramPacket(sendBuffer, sendBuffer.length,receiverHost, receiverPort);
                    mySocket.send(packet);
                break;
            //case 2: string1.concat(string2);
                    //DatagramPacket packet = new //DatagramPacket(sendBuffer, sendBuffer.length,receiverHost, receiverPort);
                    //mySocket.send(packet);
            //  break;
            //case 3: string1.endsWith(string2);
            //      DatagramPacket packet = new DatagramPacket(sendBuffer, sendBuffer.length,receiverHost, receiverPort);
                //  mySocket.send(packet);
                //break;
            //case 4: string1.startsWith(string2);
                    //DatagramPacket packet = new DatagramPacket(sendBuffer, sendBuffer.length,receiverHost, receiverPort);
                //  mySocket.send(packet);
                //break;
            //case 5: string1.indexOf(string2);
                    //DatagramPacket packet = new DatagramPacket(sendBuffer, sendBuffer.length,receiverHost, receiverPort);
                    //mySocket.send(packet);
                //break;
            }
        }
        else
            System.out.println("invalid string..");
            System.exit();
        }



    // to receive a message

    int MESSAGE_LEN = 60;
    byte[ ] recvBuffer = new byte[MESSAGE_LEN];

    DatagramPacket datagram = new DatagramPacket(recvBuffer,MESSAGE_LEN);
    mySocket.receive(datagram);
    String recvdString = new String(recvBuffer);
    System.out.println(“\n”+recvdString);

    mySocket.close( );
    }
    catch(Exception e){
    e.printStackTrace( );
    }
}
} 
Это было полезно?

Решение

Some might tell me that your question lacks minimal understanding of the problem being solved, as it's littered with compile errors, but I was curious about testing out sockets (which I never supposedly had time for before), so ironed the bugs out of your code and tested this locally.

As a result, broke it down into a reusable class, instead of just one long main method, so bear with me.

Observations:

  • Classes start with capital letters by Java naming standards. Also, constants in Java are typically defined as static final fields.

    public class DatagramSR {
      private static final int MESSAGE_LEN = 60;
    
      private DatagramSocket socket;
    
      private InetAddress host;
    
      private int port;
    
      public DatagramSR(InetAddress host, int port) throws SocketException {
        this.socket = new DatagramSocket(port, host);
        this.host = host;
        this.port = port;
      }
    
      [...]
    }
    
  • Do proper error handling instead of just catching a base exception and later wondering what went wrong, when your application doesn't work:

    public static void main(String[] args) {
      DatagramSR sr = null;
    
      try {
        InetAddress receiverHost = InetAddress.getByName(args[0]);
        int receiverPort = Integer.parseInt(args[1]);
        DatagramSocket mySocket = new DatagramSocket(receiverPort, receiverHost);
    
        sr = new DatagramSR(mySocket, receiverHost, receiverPort);
      } catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("Not enough parameters given.");
      } catch (UnknownHostException e) {
        System.out.println("Give a reasonable hostname as first parameter.");
      } catch (NumberFormatException e) {
        System.out.println("Give a reasonable port number as second parameter.");
      } catch (SocketException e) {
        System.out.println("Socket creation failed.");
      }
    
      // If it's still null, there were errors above and no point to proceed.
      if (sr != null) {
        sr.run();
      }
    }
    
  • Use Scanner for instance to get user input.

    Scanner scanner = new Scanner(System.in);
    
    System.out.println("Define term1.");
    String term1 = scanner.nextLine();
    System.out.println("Define term2.");
    String term2 = scanner.nextLine();
    
    System.out.println("To lexicographically compare terms, choose 1");
    System.out.println("To append term2 to term1, choose 2");
    System.out.println("To determine if term1 ends with term2, choose 3");
    System.out.println("To determine if term1 starts with term2, choose 4");
    System.out.println("To return the index of the first occurrence of term2 in term1, choose 5");
    
    while (true) {
      try {
        code = Integer.parseInt(scanner.nextLine());
        break;
      } catch (NumberFormatException e) {
        System.out.println("Please give an integer to proceed.");
      }
    }
    
    scanner.close();
    
  • Don't bother checking specifically, if code is within switch range. That'll just become a beastly if clause, if you add say couple dozen cases. Much easier to just throw an exception and handle it in the calling code. Also helps to DRY (Don't Repeat Yourself) up your switch code and do the common things for all cases afterwards.

    private void handleInput(String term1, String term2, int code)
        throws IOException {
      String message;
    
      switch (code) {
        case 1:
          int comparison = term1.compareTo(term2);
    
          if (comparison > 0) {
            message = term1 + " comes after " + term2 + " lexicographically";
          } else if (comparison < 0) {
            message = term1 + " comes before " + term2 + " lexicographically";
          } else {
            message = "Term1 and term2 are the same";
          }
    
          break;
        // Other cases omitted, since you said you could figure them out.
        default:
          throw new IOException("Unknown code: " + code);
      }
    
      byte[] sendBuffer = message.getBytes();
      DatagramPacket packet = new DatagramPacket(sendBuffer, sendBuffer.length,
                                                 host, port);
      socket.send(packet);
    }
    
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top