发送方法导致使用无连接套接字的消息?

时间:2014-01-21 14:41:37

标签: java sockets chat datagram

我正在使用无连接套接字来创建远程字符串处理器。用户输入两个术语和一个整数,全部用空格分隔。此输入变为两个字符串和一个整数。如果输入了无效的整数,则会显示错误消息并结束程序。如果输入了有效整数,则对这两个字符串执行某种方法。在执行该方法之后,我想将结果与我添加的单词(参见案例1)一起保存到变量并将其发送给用户。这是应用程序的发送者 - 接收者部分。有一个接收器 - 发件人部分,我没有发布。我还没有完成案例2-5。一旦我找到了如何做案例1,也许我会得到足够的指导来自己完成这些。

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( );
    }
}
} 

1 个答案:

答案 0 :(得分:0)

有些人可能会告诉我,你的问题对解决的问题缺乏最小的理解,因为它充满了编译错误,但我很好奇测试套接字(我以前从未想过有时间),所以很好地解决了这个问题。您的代码并在本地进行了测试。

结果,把它分解成一个可重复使用的类,而不是一个长的主方法,所以请耐心等待。

观察:

  • 类以Java命名标准以大写字母开头。此外,Java中的常量通常定义为static final字段。

    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;
      }
    
      [...]
    }
    
  • 执行正确的错误处理,而不仅仅是捕获基本异常,然后在您的应用程序不起作用时想知道出了什么问题:

    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();
      }
    }
    
  • 例如,使用Scanner来获取用户输入。

    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();
    
  • 如果代码在开关范围内,请不要特别检查。如果加上说几十个案例,那将只会成为一个野兽if条款。更容易抛出异常并在调用代码中处理它。也有助于干掉(不要重复自己)你的开关代码,然后为所有情况做一些常见的事情。

    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);
    }