我正在尝试为分配编写客户端和时间服务器,但我无法让服务器从客户端接收第二个请求。第一个请求顺利完成。那它只是停滞不前。我实际上已经迷失在整个事情中,而且对java仍感到不安,所以我不知道我错过了什么。任何指针都非常感谢。谢谢!
这是服务器代码:
import java.io.*;
import java.util.*;
import java.net.*;
import java.text.*;
public class myServer {
protected static final int PORT_NUMBER = 55555;
public static void main( String args[]) {
try {
ServerSocket servsock = new ServerSocket(PORT_NUMBER);
System.out.println("Server running...");
while(true) {
Socket sock = servsock.accept();
System.out.println("Connection from: " + sock.getInetAddress());
Scanner in = new Scanner(sock.getInputStream());
PrintWriter out = new PrintWriter(sock.getOutputStream());
String request = "";
request = in.next();
System.out.println("Request: " + request);
if(request.toUpperCase().equals("TIME")) {
out.println(getTime());
out.flush();
} else {
out.println("Invalid Request...");
out.flush();
}
}
} catch(Exception e) {
System.out.println(e.toString());
}
}
protected static String getTime() {
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
Date date = new Date();
return (dateFormat.format(date));
}
}
这是客户:
import java.io.*;
import java.util.*;
import java.net.*;
public class myClient {
protected static final String HOST = "127.0.0.1";
protected static final int PORT = 55555;
protected static Socket sock;
public static void main(String args[]) {
try {
sock = new Socket(HOST,PORT);
System.out.println("Connected to " + HOST + " on port " + PORT);
Scanner response = new Scanner(sock.getInputStream());
PrintWriter request = new PrintWriter(sock.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String txt = "";
while(!txt.toUpperCase().equals("EXIT")) {
System.out.print("prompt:");
txt = in.readLine();
request.println(txt);
request.flush();
System.out.println(response.next());
}
request.close();
response.close();
in.close();
sock.close();
} catch(IOException e) {
System.out.println(e.toString());
}
}
}
答案 0 :(得分:4)
你需要有另一个while循环,像这样,
while(true) {
Socket sock = servsock.accept();
System.out.println("Connection from: " + sock.getInetAddress());
Scanner in = new Scanner(sock.getInputStream());
PrintWriter out = new PrintWriter(sock.getOutputStream());
String request = "";
while (in.hasNext()) {
request = in.next();
System.out.println("Request: " + request);
if(request.toUpperCase().equals("TIME")) {
out.println(getTime());
out.flush();
} else {
out.println("Invalid Request...");
out.flush();
}
}
}
答案 1 :(得分:3)
来自PrintWriter
docs:
...如果启用了自动刷新,则只有在调用
println
,printf
或format
方法之一时才会执行此操作...
您的服务器正在调用print()
并且从不刷新流,因此永远不会发送时间。可以调用println()
或显式刷新流。
此外,服务器在发送时间后立即关闭连接,因此客户端的第二个请求总是失败...
编辑:这里有一个有趣的怪癖 - 关闭PrintWriter
应该来刷新它(参见Writer
的规范),但是到期而似乎的操作顺序是:
in.close()
关闭基础Socket
out.close()
将刷新写入的数据,但不能(因为套接字现已关闭)不确定这正是发生了什么,但是交换这两个语句的顺序会改变行为,大概会让out.close()
有机会冲洗......