从服务器接收数据时NoSuchElementFoundException

时间:2015-12-27 10:49:39

标签: java java.util.scanner

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

1 个答案:

答案 0 :(得分:1)

问题是你没有给服务器的输出写一个数字,而是一个带有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));