古詩詞大全網 - 團隊口號 - 我想用java寫壹個簡單的web server,應該怎麽寫呀?

我想用java寫壹個簡單的web server,應該怎麽寫呀?

我原來寫過壹個很簡單的,可以指定妳存放網頁的文件夾,可以指定允許訪問的IP,給妳源碼看看吧。public class WebServer {

static Button btReloadIP=new Button("更新合法IP列表");

static Button btAllow=new Button("允許此IP");

static Button btRepel=new Button("拒絕此IP");

static JTextField tfNewIP=new JTextField(20);

static JPanel pane=new JPanel();

static JTextField tfState=new JTextField(25);

static TextField tfURL=new TextField("G:\\webServer2\\",28);

static TextField tfPort=new TextField("10288",3);

static Button btStart=new Button("啟動服務器");

static Button btStop=new Button("停止服務器");

private static int IPnum=0;

public static boolean IPadmin=false;

static boolean click=false;

private static String url;

private static String[] checkIP=new String[255];

private static Thread serverThread=null;

private static Socket connectionSocket=null;

private static ServerSocket listenSocket=null;

public WebServer() throws IOException{

serverThread=new Thread(new Runnable(){

public void run(){

try {

listenSocket = new ServerSocket(Integer.parseInt(tfPort.getText()));

} catch (IOException e) { }

while(true){

try {

connectionSocket=listenSocket.accept();

@SuppressWarnings("unused")

webClient client=new webClient(connectionSocket);

} catch (IOException e) {

}

}

}

});

}

public static void main(String args[])throws Exception{

GUI();

}

public static void GUI(){

JFrame f=new JFrame("小白兔Web服務器(BY 丁尋)");

f.setSize(300,200);

f.setLocation(500, 300);

f.getContentPane().add(pane,BorderLayout.CENTER);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setVisible(true);

//不可以變大變小

f.setResizable(false);

pane.add(new JLabel("端口號:"));

pane.add(tfPort);

pane.add(btStart);

pane.add(btStop);

pane.add(new JLabel("配置路徑"));

pane.add(tfURL);

pane.add(tfState);

pane.add(new JLabel("新IP請求"));

pane.add(tfNewIP);

pane.add(btAllow);

pane.add(btRepel);

pane.add(btReloadIP); btStart.addActionListener(new Listener());

btStop.addActionListener(new Listener());

btAllow.addActionListener(new Listener());

btRepel.addActionListener(new Listener());

btReloadIP.addActionListener(new Listener());

}

static class Listener implements ActionListener {

@SuppressWarnings("deprecation")

public void actionPerformed(ActionEvent event) {

if(event.getActionCommand()=="啟動服務器"){

try {

url=tfURL.getText();

readIP();

tfState.setText("服務器已經啟動......地址:"

+InetAddress.getLocalHost().toString());

} catch (Exception e) {

e.printStackTrace();

} try {

new WebServer();

} catch (IOException e) {

e.printStackTrace();

} serverThread.start(); btStart.setEnabled(false);

tfPort.setEditable(false);

btStop.setEnabled(true);

tfURL.setEditable(false);

btReloadIP.setEnabled(true);

}

if(event.getActionCommand()=="停止服務器"){

serverThread.stop();

tfState.setText("服務器已經停止");

btStart.setEnabled(true);

tfPort.setEditable(true);

btStop.setEnabled(false);

tfURL.setEditable(true);

btReloadIP.setEnabled(false);

}

if(event.getActionCommand()=="允許此IP"){

IPadmin=true;

//serverThread.start();

click=true;

btAllow.setEnabled(false);

btRepel.setEnabled(false);

tfNewIP.setText(null);

}

if(event.getActionCommand()=="拒絕此IP"){

click=true;

IPadmin=false;

//serverThread.start();

btAllow.setEnabled(false);

btRepel.setEnabled(false);

tfNewIP.setText(null);

}

if(event.getActionCommand()=="更新合法IP列表"){

try {

readIP();

} catch (IOException e) {

// e.printStackTrace();

}

}

}

}

public static void readIP() throws IOException{

int i=0;

byte[] ips = new byte[65535];

File IPfile=new File(url+"checkIP.txt");

FileInputStream fileReader=new FileInputStream(IPfile);

fileReader.read(ips);

fileReader.close();

String strip=new String(ips);

StringTokenizer getIP=new StringTokenizer(strip,System.getProperty("line.separator"));

for(;;){

if(getIP.hasMoreTokens()){

checkIP[i]=getIP.nextToken();

System.out.println(checkIP[i]);

i++;

}

else{break;}

}

IPnum=i;

}

public static void disconnect(webClient c){

try {

//c.stop();

c.socket.close();

c.socket=null;

c=null; } catch (IOException e) {

e.printStackTrace();

}

//

}

class webClient extends Thread{

boolean check=true;

boolean send=false;

Socket socket;

BufferedReader inFromClient=null;

DataOutputStream outToClient=null;

String fileName;

String requestMessageLine;

StringTokenizer tokenizedLine=null;

FileInputStream inFile=null;

byte[] fileInBytes=null;

int numOfBytes=0;

File afile=new File(url+"log.html");

byte[] b;

public webClient(Socket s) throws IOException{

FileOutputStream out=new FileOutputStream(afile,true);

StringBuffer str=new StringBuffer();

SimpleDateFormat formatter=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

String time=formatter.format(new Date());

socket=s;

str.append(time+" Client_IP:"+socket.getInetAddress().toString()+

" Client_Port:"+socket.getPort()+"<br>"+

System.getProperty("line.separator")

);

b=(new String(str)).getBytes();

System.err.println(new String(str));

out.write(b);

out.close();

inFromClient=new BufferedReader(new

InputStreamReader(socket.getInputStream()));

outToClient=new DataOutputStream(socket.getOutputStream());

if(!checkIP(socket)){

String strWait="<html>" +

"<title>等待驗證</title>" +

"<body>正在等待管理員驗證您的IP是否合法,請稍候......<br><br>" +

"(如果頁面沒有自動跳轉,請每5秒鐘刷新壹次," +

"以判斷管理員是否已經允許您進入)</body>" +

"</html>";

byte[] waiting=strWait.getBytes();

outToClient.writeBytes("HTTP/1.1 200 Document Follows\r\n");

outToClient.writeBytes("Content-Type: text/html\r\n");

outToClient.writeBytes("Content-Length: "+waiting.length+"\r\n");

outToClient.writeBytes("\r\n");

outToClient.write(waiting,0,waiting.length);

if(!admin()){

return;

}

WebServer.IPadmin=false;

}

this.start(); }

public void receive() throws IOException{

while(socket!=null){

requestMessageLine=inFromClient.readLine();

if(requestMessageLine.length()==0){break;}

System.out.println(requestMessageLine);

tokenizedLine=new StringTokenizer(requestMessageLine);

if(tokenizedLine.hasMoreTokens()){

String strhead=tokenizedLine.nextToken();

if(strhead.equals("GET")){

send=true;

fileName=tokenizedLine.nextToken();

if(fileName.equals("/")){

fileName="index.html";

}

else if(fileName.startsWith("/")){

fileName=fileName.substring(1);

fileName=fileName.replace("%5C", "/");

fileName=fileName.replace("%20", " ");

//如果是文件 ,不要check

check=false;

}

}//endnexttoken

if(check){

if(strhead.equals("User-Agent:")){

if(requestMessageLine.contains("Firefox/3")){

System.err.println("true");

}

else{

System.err.println("false");

fileName="ERROR.html";

send=true;

}

}

}

//....

}//endhastoken

}//endwhile

if(send){

readFile();

send(fileInBytes, numOfBytes);

} }

public void send(byte[] fileInBytes,int numOfBytes) throws IOException{

outToClient.writeBytes("HTTP/1.1 200 Document Follows\r\n"); if(fileName.endsWith(".jpg")){

outToClient.writeBytes("Content-Type: image/jpg\r\n");

}

else if(fileName.endsWith(".gif")){

outToClient.writeBytes("Content-Type: image/gif\r\n");

}

else if(fileName.endsWith(".wmv")){

outToClient.writeBytes("Content-Type: video/x-ms-wmv\r\n");

}

else if(fileName.endsWith(".avi")){

outToClient.writeBytes("Content-Type: video/avi\r\n");

}

else if(fileName.endsWith(".html")||fileName.endsWith(".htm")){

outToClient.writeBytes("Content-Type: text/html\r\n");

}

outToClient.writeBytes("Content-Length: "+numOfBytes+"\r\n"); outToClient.writeBytes("\r\n");

outToClient.write(fileInBytes,0,numOfBytes);

}

//得到文件

public void readFile() throws IOException{

File file=new File(url+fileName);

b=(" Client_Request:"+fileName+"<br>"+

System.getProperty("line.separator")).getBytes();

FileOutputStream out=new FileOutputStream(afile,true);

out.write(b);

out.close();

numOfBytes=(int)file.length();

inFile=new FileInputStream(url+fileName);

fileInBytes=new byte[numOfBytes];

inFile.read(fileInBytes);

inFile.close(); }

public boolean checkIP(Socket skt){

for(int i=0;i<WebServer.IPnum;i++){

if(skt.getInetAddress().toString().equals(checkIP[i])){

return true;

}

}

return false;

}

public boolean admin() throws IOException{

WebServer.tfNewIP.setText("IP:"+socket.getInetAddress().toString()+

" PORT:"+socket.getPort());

WebServer.btAllow.setEnabled(true);

WebServer.btRepel.setEnabled(true);

while(!click){}

click=false;

if(WebServer.IPadmin){

File IPFile=new File(url+"checkIP.txt");

FileOutputStream appIP=new FileOutputStream(IPFile,true);

byte[] ips=(socket.getInetAddress().toString()+

System.getProperty("line.separator")).getBytes();

appIP.write(ips);

appIP.close();

//WebServer.readIP();

WebServer.checkIP[IPnum]=socket.getInetAddress().toString();

WebServer.IPnum++;

return true;

}

else{

WebServer.disconnect(this);

return false;

}

}

public void run(){

try {

receive();

} catch (IOException e) {

}

WebServer.disconnect(this);

}

}}