本帖最后由 777666 于 2018-5-29 01:14 编辑
public class MyServer {
public static void main(String[] args) throws Exception {
// 解析XML:
// 创建解析器
SAXReader reader = new SAXReader();
// 解析XML文档:
Document document = reader.read("conf/server.xml");
Element element = (Element)document.selectSingleNode("//Connector['@port']");
String port = element.attributeValue("port");
// ServerSocket 对象可以监听端口
ServerSocket serversocket = new ServerSocket(Integer.parseInt(port));
while(true) {
Socket socket = serversocket.accept(); // 等待客户端的连接请求,一旦有请求过来,就结束阻塞,返回客户端对象
//System.out.println(socket.getInetAddress());
// 一旦有客户来访问, 就另开一个新线程去提供服务, main线程继续等待下一个客户的连接
new Thread(new MyService(socket)).start();
}
}
}
public class MyService implements Runnable{
private Socket socket;
public MyService(Socket socket) throws Exception {
this.socket = socket;
}
@Override
public void run() {
// 提供服务
try{
InputStream in = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String firstLine = reader.readLine();
System.out.println(firstLine);
String path = firstLine.split(" ")[1];
System.out.println(path);
// 从文件读, 往浏览器写
File file = new File("webapps"+path);
FileInputStream fis = new FileInputStream(file);
OutputStream os = socket.getOutputStream();
os.write("HTTP/1.1 200 OK\r\n".getBytes());
os.write("\r\n".getBytes());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer))!=-1) {
os.write(buffer, 0, len);
}
socket.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
|
|