我正在编写一个小型 Web 服务器,它使用 3000
端口返回 Hello
:
import java.net.ServerSocket;
import java.net.Socket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class HttpServer {
public static void main(String[] args) throws Throwable {
//http://localhost:3000
ServerSocket ss = new ServerSocket(3000);
while (true) {
//Waiting for socket
Socket s = ss.accept();
System.out.println("Client accepted");
//The main process
new SocketProcessor(s,ss).start();
}
}
private static class SocketProcessor implements Runnable {
private Thread t;
private Socket s;
private ServerSocket ss;
private InputStream is;
private OutputStream os;
private SocketProcessor(Socket s,ServerSocket ss) throws Throwable {
t = new Thread(this, "Server Thread");
this.ss=ss;
this.s = s;
this.is = s.getInputStream();
this.os = s.getOutputStream();
}
public void run() {
try {
readInputHeaders();
writeResponse("<html><body><h1>Hello</h1></body></html>");
} catch (Throwable t) {
/*do nothing*/
} finally {
try {
s.close();
} catch (Throwable t) {
}
}
System.out.println("Client processing finished");
}
public void start()
{
t.start();
}
private void writeResponse(String s) throws Throwable {
String response = "HTTP/1.1 200 OK\r\n" +
"Server: Server\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length: " + s.length() + "\r\n" +
"Connection: close\r\n\r\n";
String result = response + s;
os.write(result.getBytes());
os.flush();
}
private void readInputHeaders() throws Throwable {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while(true) {
String s = br.readLine();
System.out.println(s);
if(s == null || s.trim().length() == 0) {
break;
}
}
}
}
}
我想让我的服务器在响应之前等待一秒。我试图使用这样的东西:
readInputHeaders();
t.wait(1000);
writeResponse("<html><body><h1>Hello</h1></body></html>");
但我的浏览器显示ERR_EMPTY_RESPONSE
最佳答案
在SocketProcessor
的run方法中调用Thread.sleep(1000)
。
wait
方法不适合您的目的。
另请参阅:
方法wait
、notify
、notifyAll
在java.lang.Object
上定义
并用于线程之间的同步。它们通常不是
目的是使线程 hibernate 一定时间。
关于java - 如何让我的网络服务器等待?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22819718/