欢迎来到天天文库
浏览记录
ID:59343396
大小:31.50 KB
页数:7页
时间:2020-09-04
《用JAVA编写Web服务器.doc》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、WebServer.java用JAVA编写Web服务器//WebServer.java用JAVA编写Web服务器importjava.io.*;importjava.net.*;publicclassWebServer{publicstaticvoidmain(Stringargs[]){inti=1,PORT=8080;ServerSocketserver=nul//WebServer.java用JAVA编写Web服务器importjava.io.*;importjava.net.*;publicclassWebServer{publicstatic
2、voidmain(Stringargs[]){inti=1,PORT=8080;ServerSocketserver=null;Socketclient=null;try{server=newServerSocket(PORT);System.out.println("WebServerislisteningonport"+server.getLocalPort());for(;;){client=server.accept();//接受客户机的连接请求newConnectionThread(client,i).start();i++;}}catch(
3、Exceptione){System.out.println(e);}}}/*ConnnectionThread类完成与一个Web浏览器的通信*/classConnectionThreadextendsThread{Socketclient;//连接Web浏览器的socket字intcounter;//计数器publicConnectionThread(Socketcl,intc){client=cl;counter=c;}publicvoidrun()//线程体{try{StringdestIP=client.getInetAddress().toS
4、tring();//客户机IP地址intdestport=client.getPort();//客户机端口号System.out.println("Connection"+counter+":connectedto"+destIP+"onport"+destport+".");PrintStreamoutstream=newPrintStream(client.getOutputStream());DataInputStreaminstream=newDataInputStream(client.getInputStream());Stringinli
5、ne=instream.readLine();//读取Web浏览器提交的请求信息System.out.println("Received:"+inline);if(getrequest(inline)){//如果是GET请求Stringfilename=getfilename(inline);Filefile=newFile(filename);if(file.exists()){//若文件存在,则将文件送给Web浏览器System.out.println(filename+"requested.");outstream.println("HTTP/1
6、.0200OK");outstream.println("MIME_version:1.0");outstream.println("Content_Type:text/html");intlen=(int)file.length();outstream.println("Content_Length:"+len);outstream.println("");sendfile(outstream,file);//发送文件outstream.flush();}else{//文件不存在时Stringmsg1="
7、ound
8、tream.close();//outstream.close();longm1=1;//延时
此文档下载收益归作者所有