我正在使用以下代码来学习java套接字编程。它的作用是,client.java 程序从用户那里获取一个号码并将其发送到 sever.java。然后服务器将其乘以2并发回给客户端。在我的客户端程序中,它成功地将用户输入发送到服务器,但服务器卡在 number=sc.nextInt();
行等待。但是,如果我关闭 client.java 程序,它会显示 sever.java 程序确实收到了客户端发送的内容,并以正确的结果终止该程序。
client.java
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
public class client {
public static void main(String args[]) throws IOException
{
int number, temp;
Scanner sc = new Scanner (System.in);
Socket s = new Socket ("127.0.0.1",6666);
Scanner sc1 = new Scanner (s.getInputStream());
System.out.println("Enter any number");
number = sc.nextInt();
PrintStream p = new PrintStream(s.getOutputStream());
p.print(number);//passing the number to the sever
System.out.println("after passing the number");//Never reach here
temp=sc1.nextInt();
System.out.println(temp);
}
}
服务器.java
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class sever {
public static void main(String args[]) throws IOException
{
System.out.println("sever starting");
int number, temp;
ServerSocket s1=new ServerSocket(6666);
Socket ss=s1.accept();
Scanner sc=new Scanner(ss.getInputStream());
number=sc.nextInt(); //Program waits here unless I close the client
System.out.println("this part never get executed: "+number);
temp = number*2;//doesn't reach here till I close the client program
System.out.println("Result temp: "+temp);
PrintStream p=new PrintStream(ss.getOutputStream());
p.print(temp);
}
}
最佳答案
客户端正在发送输入的号码,不带任何终止符,例如42
。服务器上的 Scanner
看到 42
但不知道这是否是完整的数字,因此它会等待,直到连接关闭或收到空格。
通过在客户端上使用 println
轻松修复。
您可能还需要刷新
数据,如suggested by Vince Emigh :
Flush the output by calling
PrintStream#flush
after printing the data, or change the constructor arguments to auto-flush.
您可能也想在服务器上使用 println
和 flush
,但由于服务器退出并因此关闭连接,客户端将完成 sc1 .nextInt()
无论如何调用。
关于Java套接字程序卡在sc.nextInt()处;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51353727/