你好,写一个client端,代码如下:
import java.net.*;
import java.io.*;
public class DateClient {
static final int LISTENING_PORT = 32007;
public static void main(String[] args) {
String computer; // Name of the computer to connect to.
Socket connection; // A socket for communicating with
// that computer.
Reader incoming; // Stream for reading data from
// the connection.
/* Get computer name from command line. */
if (args.length > 0)
computer = args[0];
else {
// No computer name was given. Print a message and exit.
System.out.println("Usage: java DateClient
return;
}
/* Make the connection, then read and display a line of text. */
try {
connection = new Socket( computer, LISTENING_PORT );
incoming = new InputStreamReader( connection.getInputStream() );
while (true) {
int ch = incoming.read();
if (ch == -1 || ch == '\n' || ch == '\r')
break;
System.out.print( (char)ch );
}
System.out.println();
incoming.close();
}
catch (IOException e) {
TextIO.putln("Error: " + e);
}
// end main()
} // end class DateClient
再写一个服务端,代码如下:
import java.net.*;
import java.io.*;
import java.util.Date;
public class DateServe {
static final int LISTENING_PORT = 32007;
public static void main(String[] args) {
ServerSocket listener; // Listens for incoming connections.
Socket connection; // For communication with the
// connecting program.
/* Accept and process connections forever, or until
some error occurs. (Note that errors that occur
while communicating with a connected program are
caught and handled in the sendDate() routine, so
they will not crash the server.)
*/
try {
listener = new ServerSocket(LISTENING_PORT);
TextIO.putln("Listening on port " + LISTENING_PORT);
while (true) {
connection = listener.accept();
sendDate(connection);
}
}
catch (Exception e) {
TextIO.putln("Sorry, the server has shut down.");
TextIO.putln("Error: " + e);
return;
}
} // end main()
static void sendDate(Socket client) {
// The parameter, client, is a socket that is
// already connected to another program. Get
// an output stream for the connection, send the
// current date, and close the connection.
try {
System.out.println("Connection from " +
client.getInetAddress().toString() );
Date now = new Date(); // The current date and time.
PrintWriter outgoing; // Stream for sending data.
outgoing = new PrintWriter( client.getOutputStream() );
outgoing.println( now.toString() );
outgoing.flush(); // Make sure the data is actually sent!
client.close();
}
catch (Exception e){
System.out.println("Error: " + e);
}
} // end sendDate()
} //end class DateServe
发起客户端请求就可以得到服务器时间了!
<--温馨提示-->
真心希望你能采纳我的回答,如有不明白,可以继续追问,若满意,记得及时采纳。
首先知道http请求是短连接,一次请求和响应与系一个请求相应没有关系
你想获得当前时间后,在一个小时之内继续可以才提交,主要是设置session的时间
这个在web.xml里面就可以配置