如何在java中从用户处读取字符串(套接字编程)
我正在编写一个客户机/服务器程序。当我尝试使用scanner.nextLine()从客户端读取字符串时,它不会等待在控制台上写入文本并处理下一条语句。我用二进制I/O编写程序,因为它比文本I/O更有效如何在java中从用户处读取字符串(套接字编程),java,sockets,Java,Sockets,我正在编写一个客户机/服务器程序。当我尝试使用scanner.nextLine()从客户端读取字符串时,它不会等待在控制台上写入文本并处理下一条语句。我用二进制I/O编写程序,因为它比文本I/O更有效 DataInputStream fromServer = null; DataOutputStream toServer = null; Scanner scanner = new Scanner(System.in); try{ socket
DataInputStream fromServer = null;
DataOutputStream toServer = null;
Scanner scanner = new Scanner(System.in);
try{
socket = new Socket("localhost",8000);
toServer = new DataOutputStream
(socket.getOutputStream());
fromServer = new DataInputStream
( socket.getInputStream());
}
catch(IOException e){
System.out.println(" Error in connection: " + e);
e.printStackTrace();
}
System.out.println("Connection is successfully Established...");
try{
//This does not processing
setText = scanner.nextLine();
toServer.writeUTF(setText);
toServer.flush();
// Get area from the server
double area = fromServer.readDouble();
// Display to the text area
System.out.println("Text from Client " + setText + "\n");
System.out.println("Response from server " + area + '\n');
}
catch(IOException e){
System.out.println(" Error in connection: " + e);
e.printStackTrace();
}
输出为:
Text from Client
Response from server 45.22
如您所见,该程序不从控制台获取输入
如果我使用next()而不是nextLine(),那么它运行良好,但是我想读一行文本,直到输入键。服务器发送delim新行字符,所以
readLine
不会挂起吗?这是您的全部代码还是在您进入显示的部分之前,scanner
还有其他用途?setText是字符串,是的,我之前使用scanner对象从用户和当我使用另一个scanner类对象时,它运行良好。感谢服务器发送delim新行字符,所以readLine
不会挂起?这是您的全部代码,还是在您进入显示的部分之前,scanner
还有其他用途?setText是字符串,是的,我以前使用scanner对象从用户获取输入,当我使用另一个scanner类对象时,它会被删除运行良好。感谢服务器发送delim新行字符,所以readLine
不会挂起?这是您的全部代码,还是在您进入显示的部分之前,scanner
还有其他用途?setText是字符串,是的,我以前使用scanner对象从用户获取输入,当我使用另一个scanner类对象时,它会被删除运行良好。谢谢你