📄 simeplewebserver.java
字号:
//一个监听端口并提供HTML文档的程序.
import java.io.*;
import java.net.*;
class SimpleWebServer {
public static void main(String args[]) {
ServerSocket serverSocket = null;
Socket clientSocket = null;
int connects = 0;
try {
// 建立一个服务器套接字
serverSocket = new ServerSocket(8089, 5);
while (connects < 5) {
// 等待连接
clientSocket = serverSocket.accept();
//服务连接
ServiceClient(clientSocket);
connects++;
}
serverSocket.close();
}catch (IOException ioe) {
System.out.println("Error in SimpleWebServer: " + ioe);
}
}
public static void ServiceClient(Socket client) throws IOException {
DataInputStream inbound = null;
DataOutputStream outbound = null;
try {
// 得到IO流
inbound = new DataInputStream( client.getInputStream());
outbound = new DataOutputStream( client.getOutputStream());
//格式化输出(回应头和很少的HTML文档)
StringBuffer buffer = new StringBuffer();
buffer.append("Server Documents");
String inputLine;
while ((inputLine = inbound.readLine()) != null){
//如果到了HTTP请求的尾部,就发送回应
if ( inputLine.equals("") ) {
outbound.writeBytes(buffer.toString());
break;
}
}
}catch (IOException ioe) {
System.out.println("Error in SimpleWebServer: " + ioe);
}finally {
//关闭输入输出流和套接字
System.out.println("Cleaning up connection: " + client);
outbound.close();
inbound.close();
client.close();
client.close();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -