在DatagramSocket服务器中将字符串转换为int的java
我正在使用this site上的代码创建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
以下是新一期的输出:
Starting game...
Client connection established! Game started
Button 1 turned on
Player pressed button 1
strlength pre trim = 1024
strlen post trim = 1
Correct!
Button 12 turned on
Player pressed button 12
strlength pre trim = 1024
strlen post trim = 2
Correct!
Button 1 turned on
Player pressed button 12
strlength pre trim = 1024
strlen post trim = 2
Incorrect!
Game over!
Score: 2 points
第三次迭代就是问题所在。客户端向服务器发送了“1”,但被读取为“12”
# 1 楼答案
在分析句子变量之前,请确保删去了它上面多余的空格
从您的例外情况来看,它看起来没有空格,但可能是一个不可打印的字符潜入字符串中