Java 在DatagramSocket服务器中将字符串转换为int

Java 在DatagramSocket服务器中将字符串转换为int,java,datagram,numberformatexception,Java,Datagram,Numberformatexception,我正在使用上找到的代码创建UDP客户端和服务器。我的代码一直在运行,现在我无法将从客户端发送到服务器的字符串转换为整数 我遇到的问题是udpServer java文件第57行有一个NumberFormatException 以下是错误的输出: Starting game... Client connection established! Game started Button 10 turned on Exception in thread "Thread-0" java.lang.Numbe

我正在使用上找到的代码创建UDP客户端和服务器。我的代码一直在运行,现在我无法将从客户端发送到服务器的字符串转换为整数

我遇到的问题是udpServer java文件第57行有一个NumberFormatException

以下是错误的输出:

Starting game...
Client connection established! Game started

Button 10 turned on
Exception in thread "Thread-0" java.lang.NumberFormatException: For input string: "10"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:492)
    at java.lang.Integer.parseInt(Integer.java:527)
    at ie.dit.student.briscoe.brian.udpServer.run(udpServer.java:57)
这是服务器

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

import java.util.Random;

class udpServer extends Thread
{
   private DatagramSocket serverSocket;
   int score;

   /* Declaring the constructor for this class */
   public udpServer(int port) throws IOException
   {
      /* This line creates a new server socket and uses the 
       * port number variable as the parameter */
      serverSocket = new DatagramSocket(port);

      /* This line sets the timeout for the server to 10 seconds.
       * This means that the server will wait for connections for 
       * 10 seconds and close if no connections are received in that
       * time*/
      serverSocket.setSoTimeout(5000);
   }

   public void run()
   {
      System.out.println("Starting game...");
      System.out.println("Client connection established! Game started");
      byte[] receiveData = new byte[1024];
      byte[] sendData = new byte[1024];
      int buttonInt, randInt;
      Random rand;
      String sentence, capitalizedSentence;

         while(true)
         {
            try 
            {
               rand = new Random();
               randInt = 1 + rand.nextInt(12);  
               System.out.println("\nButton " + randInt + " turned on");

               DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
               serverSocket.receive(receivePacket);
               sentence = new String(receivePacket.getData());

/*line 57*/    buttonInt = Integer.parseInt(sentence);

               if(buttonInt == randInt)
               {
                    System.out.println("Player pressed the correct button");
                    score += 1;
               }// End

               else
               {
                    System.out.println("Incorrect button pressed\nGame over!");
                    System.out.println("Score = " + score);
                    break;
               }// End else

               //System.out.println("RECEIVED: " + sentence);
               InetAddress IPAddress = receivePacket.getAddress();
               int port = receivePacket.getPort();
               capitalizedSentence = sentence.toUpperCase();
               sendData = capitalizedSentence.getBytes();
               DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
               serverSocket.send(sendPacket);
            }// End try

            catch (SocketTimeoutException s)
            {   
                /* Informing the user of the error that happened */
                System.out.println("Time up\nGame over!");
                //System.out.println("Score = " + score);

                /* Exiting the program */
                break;
            }// End catch

            catch (IOException i)
            {
               i.printStackTrace();
            }// End catch
         }
   }

   /*The start of the main loop */
   public static void main(String [] args)
   {
      /* This line creates and initialises a variable to store the port number used
       * for the connection */
      int port = 4444;
      try
      {
         /* This line creates a new thread which is an instance of this class
          * with the port number supplied by the user as an argument as the port
          * number for the server */
         Thread t = new udpServer(port);

         /* Start the thread */
         t.start();

      }// End try

      /* This will be satisfied if some sort of input/output error has occurred */
      catch(IOException e)
      {  

         e.printStackTrace();
      }// End catch
   }// End main()
}
这是客户

import java.io.*;
import java.net.*;
class udpClient
{
  public static void main(String args[])
  {
     String serverName = "localhost";
     int port = 4444;
     while(true)
     {
        try
        {
           DatagramSocket clientSocket = new DatagramSocket();
           BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
           Console console = System.console();

           String userStr = console.readLine("Read the server window to see which button to press: ");

           if(userStr != null)
           {
              try
              {
                 int temp = Integer.parseInt(userStr);

                 if(temp > 0 && temp < 13)
                 {
                    System.out.println("You pressed button " + userStr);
                    InetAddress IPAddress = InetAddress.getByName(serverName);
                    byte[] sendData = new byte[1024];
                    byte[] receiveData = new byte[1024];
                    //String sentence = inFromUser.readLine();
                    sendData = userStr.getBytes();
                    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
                    clientSocket.send(sendPacket);
                    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                    clientSocket.receive(receivePacket);
                    String modifiedSentence = new String(receivePacket.getData());
                    System.out.println("FROM SERVER:" + modifiedSentence);
                    clientSocket.close();  
                 }// End if

                 else
                 {
                    System.out.println("Invalid input value not in range\nGame over");
                    clientSocket.close();
                 }// End else
              }// End try

              catch(NumberFormatException n)
              {
                 System.out.println("Invalid input\nGame over");
                 clientSocket.close();
              }// End catch
           }// End if

           else
           {
              System.out.println("Invalid input userstr = null\nGame over");
              clientSocket.close();
           }

           /* Closing the socket client connection */
           clientSocket.close();

        }// End try

        catch(IOException e)
        {
           /* This will print the technical specification of the error that has
            * occurred */
           e.printStackTrace();
           break;
        }// End catch
     }// End infinite while loop
  }// End main()
}// End class udpClient

第三次迭代就是问题所在。客户端向服务器发送了1,但它被读取为12

在解析句子变量之前,请确保删掉多余的空格

buttonInt = Integer.parseInt(sentence.trim());

从您的异常情况来看,似乎没有空格-但可能是一个不可打印的字符潜入字符串。

输入字符串真的是10吗?如果是这样的话,我不理解这个例外。我猜里面也有无法打印的字符。首先尝试记录字符串的长度…谢谢您的评论。字符串长度为1024预修剪。当客户端发送号码时,它工作正常。但是,如果数字是一位数字,则上一个数字的最后一位数字将连接到末尾。这是输出按钮10打开播放器按下按钮10 strlength=1024正确!按钮7打开播放器按下按钮70 strlength=1024不正确!我已经更新了我的原始帖子,以更可读的格式包含输出。如果您能查看它以了解我的问题,我将不胜感激。谢谢这帮助了我的问题!然而,仍然有一个小问题。每当从客户端向服务器发送一位数字时,前一个数字字符串的最后一个字符将添加到该数字字符串中,从而结束游戏。下面是示例输出:按钮10打开播放器按下按钮10 strlength=1024正确!按钮7打开播放器按下按钮70 strlength=1024不正确!我已经更新了我的原始帖子,以更可读的格式包含输出。如果你能看一下,了解一下我的问题,我将不胜感激。
buttonInt = Integer.parseInt(sentence.trim());