📄 phttpd.java
字号:
// 模仿HTTP服务器程序Phttpd.java
// 此程序利用端口号8001运行的服务器程序
// 运行方式:java Phttp 数据文件名
// 对于WWW客户端的连接请求,回送用参数指定的文件
// 利用的库
import java .io.* ;
import java.net.* ;
import java.util.* ;
// Phttpd类
class Phttpd{
public static void main(String args[]){
// 准备服务器socket
ServerSocket servsock = null ;
Socket sock ;
// 准备输入输出
OutputStream out ;
BufferedReader in ;
FileInputStream infile = null;
byte[] buff = new byte[1024];
// 其他参数
boolean cont = true ;
int i ;
try{
// 生成服务器socket(端口号为8001)
servsock = new ServerSocket(8001,300) ;
while(true){
sock = servsock.accept() ;// 接收连接请求
// 显示连接端口
System.out.println("连接请求"
+ (sock.getInetAddress()).getHostName()) ;
// 生成对象文件infile,准备文件
try
{
infile = new FileInputStream(args[0]) ;
}
catch(Exception e){
// 文件准备失败
System.err.println("没有找到文件") ;
System.exit(1) ;
}
// 生成读写对象
in = new BufferedReader(new
InputStreamReader(sock.getInputStream()));
out = sock.getOutputStream() ;
// 暂时跳过2个换行符的读取
for(i = 0; i < 2;++i)
in.readLine() ;
// 输出文件
cont = true ;
while(cont){
// 从文件中读取数据并发送到网络
try{
int n = infile.read(buff);
out.write(buff,0,n) ;
}
catch(Exception e){
cont = false ;
}
}
// 连接结束
sock.close() ;
infile.close() ;
}
}catch(IOException e){
System.exit(1) ;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -