欢迎来到天天文库
浏览记录
ID:38270015
大小:324.34 KB
页数:5页
时间:2019-06-07
《Java——简单Web服务器实现》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、这是一个简单的Web服务器实现,主要功能就是根据用户请求在同一文件夹下查找对应文件并传输,找不到就传输错误页面。及运行截图如下://测试网页在同一文件夹下importjava.io.*;importjava.net.*;importjava.util.*;importjava.awt.*;importjavax.swing.*;publicclassMultiThreadServerextendsJFrame{privateJTextAreajta=newJTextArea();publicstati
2、cvoidmain(String[]args){newMultiThreadServer();}publicMultiThreadServer(){setLayout(newBorderLayout());//createtheGUIadd(newJScrollPane(jta),BorderLayout.CENTER);setTitle("MultiThreadServerbyLiZhaoji");setSize(500,300);setDefaultCloseOperation(JFrame.EX
3、IT_ON_CLOSE);setVisible(true);try{ServerSocketserverSocket=newServerSocket(8080);//waitrequestonport8080jta.append("MultiThreadServerstartedat"+newDate()+'');jta.append("WebServerislisteningonport"+serverSocket.getLocalPort()+''+'');intclientNo=1;
4、while(true){Socketsocket=serverSocket.accept();//waitforrequestjta.append("*****************************************************************************"+'');jta.append("Startingthreadforclient"+clientNo+"at"+newDate()+'');InetAddressinetAddress=soc
5、ket.getInetAddress();//gettheclientinformationjta.append("Client"+clientNo+"'shostnameis"+inetAddress.getHostName()+'');jta.append("Client"+clientNo+"'sIPAddressis"+inetAddress.getHostAddress()+'');HandleAClienttask=newHandleAClient(socket);newThrea
6、d(task).start();//createanewthreadhandletherequestclientNo++;}}catch(IOExceptionex){System.err.println(ex);}}classHandleAClientimplementsRunnable{privateSocketsocket;publicHandleAClient(Socketsocket){this.socket=socket;}publicvoidrun(){try{BufferedReade
7、rinputFromClient=newBufferedReader(newInputStreamReader(socket.getInputStream()));PrintStreamoutputToClient=newPrintStream(socket.getOutputStream());Stringurl=inputFromClient.readLine();jta.append("TheServerhasarequest"+"***"+url+"***"+'');if(url.star
8、tsWith("GET")){//gettherequest'sdocumentnameif(url.indexOf("HTTP/")>4){Stringfilename=url.substring(5,url.indexOf("HTTP/")-1);Filefile=newFile(filename);if(file.exists()){//ifthefileexistintheserverjta.append("filecanbefind!!!"+'
此文档下载收益归作者所有