java中的简单客户端 - 服务器应用程序沟通问题

时间:2013-12-01 19:35:09

标签: java tcp client-server

我在尝试从客户端向服务器发送命令时遇到了这些异常:

    Exception in thread "Thread-0" java.lang.NullPointerException
    at pl.polsl.java.lab.server.ServerModel.reactForRequest(ServerModel.java:17)
    at pl.polsl.java.lab.server.SingleService.run(ServerControler.java:82)

我的服务器类: 服务器控制器代码:

     package pl.polsl.java.lab.server;

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

      /** 
       * The main class of the server
       * 
       * @author sliwkacz
       * 
       */
      public class ServerControler {

          /** port number */
          static final int PORT = 9997;

          /** 
           * The main application method
           * 
           * @params args all parametres are ignored
           */
          public static void main(String args[]) throws IOException {
              ServerSocket server = new ServerSocket(PORT);
              System.out.println("Server started");

              try {
                  while (true) {
                      Socket socket = server.accept();
                      try {
                          new SingleService(socket);
                      } catch (IOException e) {
                          socket.close();
                          System.err.println(e.getMessage());
                      }
                  }
              } finally {
                  server.close();
              }
          }
      }

      /** 
       * The server class servicing a single connection 
       */
      class SingleService extends Thread {

  /** socket representing connection to the client */
   private Socket socket;
  /** buffered input character stream */
  private BufferedReader in;
  /** Formatted output character stream */
  private PrintWriter out;

  /** 
   * The constructor of instance of the SingleService class. Use the socket as a parameter.
   * 
   * @param socket socket representing connection to the client
   */
  public SingleService(Socket socket) throws IOException {
    this.socket = socket;
    out = new PrintWriter(
            new BufferedWriter(
            new OutputStreamWriter(
            socket.getOutputStream())), true);
    in = new BufferedReader(
            new InputStreamReader(
            socket.getInputStream()));
    start();
  }

  /** 
   * Realizes the service 
   */
  boolean first=true;
  @Override
  public void run() {
    try {
        out.println("Type 'help' to get command list...");
        while (true) {
            String str = in.readLine();
            if(!first){
            String answer = ServerModel.reactForRequest(str);
            if (str.equalsIgnoreCase("quit")) {
                out.println("Server answers: Goodbye!");
                break;
            }
            out.println("Server answers: " + answer);

            System.out.println("Client sent: " + str);
            }else{
                out.println("HELLO!");
                first=false;
            }
        }
        System.out.println("closing...");
    } catch (IOException e) {
        System.err.println(e.getMessage());
    } finally {
        try {
            socket.close();         
        } catch (IOException e) {
            System.err.println(e.getMessage());
        }
    }
     }
      }

服务器型号代码:

    package pl.polsl.java.lab.server;

    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.Random;
    /** 
     * The class of the server's answers
     * 
     * @author sliwkacz
     * 
     */
    public class ServerModel {
public static String reactForRequest(String input){
    String answer="";
    if(input.equalsIgnoreCase("date")){
        DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        Date today = Calendar.getInstance().getTime();  
        answer = "Today's date is: "+df.format(today);
    }else
    if(input.equalsIgnoreCase("dayofayear")){
        Calendar calendar = Calendar.getInstance();
        int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR);  
        answer="Today is "+dayOfYear+" day of the year.";
    }else
    if(input.equalsIgnoreCase("daysleft")){
        Calendar calendar = Calendar.getInstance();
        int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR);  
        answer=""+(365-dayOfYear)+" days left this year.";
    }else
    if(input.equalsIgnoreCase("random")){
        Random rand = new Random();
        int number = rand.nextInt();
        answer="This is a random numer: "+number;
    }else
    if(input.equalsIgnoreCase("help")){
        answer="Try commands: date, dayofyear, daysleft, random.";
    }

    else answer="I don't know what you want from me... Type 'help' for command list.";
    return answer;
}
    }

我的CLient类代码:

package pl.polsl.java.lab.client;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;
/** 
* The main class of the client
* 
 * @author sliwkacz
* 
*/
public class ClientView {
static final int PORT = 9997;
public static void main(String argv[]) throws Exception
 {
  System.out.println("Start communicating...");
  String sentence;
  String modifiedSentence;
  BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
  Socket clientSocket = new Socket("localhost", PORT);
  DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
  BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
  sentence = inFromUser.readLine();
  outToServer.writeBytes(sentence + '\n');
  modifiedSentence = inFromServer.readLine();
  System.out.println("FROM SERVER: " + modifiedSentence);
  clientSocket.close();`enter code here`
 }
}

我可以在运行服务器项目和“开始通信...”信息时看到“服务器启动”信息,同时运行runnig客户端项目。每次我尝试从客户端向服务器发送任何类型的命令时,都会弹出这些错误。 我会非常感谢你的帮助。

1 个答案:

答案 0 :(得分:1)

问题涉及ServerControler.run中的while循环您正在调用:

String str = in.readLine();

in是一个从套接字读取的扫描程序,由于另一方尚未发送任何内容,str为空。然后以reactForRequest作为参数调用str,从而产生NullPointerException。您真正想要做的是从控制台中读取。