public class cli
{
public static void main(String args[]) throws IOException
{
int no,rec;
Scanner sc = new Scanner(System.in);
Socket s = new Socket("127.0.0.1", 1400);
Scanner sc1 = new Scanner(s.getInputStream());
System.out.println("Enter any number");
no = sc.nextInt();
PrintStream ps = new PrintStream(s.getOutputStream());
ps.println(no);
rec = sc1.nextInt();
System.out.println("Receive number is " + rec);
}
}
我正在向服务器发送一个数字并得到一个数字,该数字是发送数字的倍数,但我面临的问题是:rec=sc1.nextInt()
语句给了我 NoSuchElementFoundException
。我究竟做错了什么?谢谢。
服务器代码:
public class Server {
public static void main(String args[]) throws IOException {
ServerSocket ss = new ServerSocket(1400);
System.out.println("Waiting ");
Socket s1 = ss.accept();
Scanner sc = new Scanner(s1.getInputStream());
int a = sc.nextInt();
int temp = 2 * a;
PrintWriter ps = new PrintWriter(s1.getOutputStream());
ps.write(temp);
ps.flush();
System.out.println("Got and sent Sucessfull " + temp);
ss.close();
}
}
最佳答案
问题是您没有向服务器的输出写入一个数字,而是一个带有 2*a 代码的字符。
int temp = 2 * a;
PrintWriter ps = new PrintWriter(s1.getOutputStream());
ps.write(temp);
这里调用write(temp)
将带有 temp
代码的字符写入输出。例如,如果 a
为 16,则 temp
为 32,因此将其写入 PrintWriter
实际上写入了一个空格字符。如果您想将数字写成字符串,请执行以下操作:
ps.write(Integer.toString(temp));
关于java - 从服务器接收数据时出现 NoSuchElementFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34479681/