java 写server_我想用java写一个简单的web server,应该怎么写呀?

展开全部

我原来写过一个很简单的,可以指定你存放网页的文件e68a84e8a2ad62616964757a686964616f31333332623931夹,可以指定允许访问的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()+"
"+

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="" +

"

等待验证" +

"

正在等待管理员验证您的IP是否合法,请稍候......
" +

"(如果页面没有自动跳转,请每5秒钟刷新一次," +

"以判断管理员是否已经允许您进入)" +

"";

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+"
"+

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

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);

}

}}

2Q==

已赞过

已踩过<

你对这个回答的评价是?

评论

收起

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值