📄 servertest.java
字号:
package web.http.test;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.io.RandomAccessFile;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
public class ServerTest
{
/**
* HTTP协议的端口
*/
private int PORT = 80;
/**
* HTTP协议的服务器端
*/
private ServerSocket server = null;
/**
* 用户数目
*/
private int userNumber = 1;
/**
* 服务的路径
* 从配置文件中读取
* 配置文件为简单ini 类型
*/
private String serverPath=null;
/**
* 日志记录,记录一些客户访问信息
*/
private RandomAccessFile infoLog=null;
/**
* 日志记录,记录错误信息
*/
private RandomAccessFile errorLog=null;
/**
* 显示系统错误时,弹出窗口时需要的容器:界面窗口
*
*/
private JComponent parentComponent=null;
/**
* 显示提示信息的窗口
*/
private JTextArea taInfo=null;
public static void main(String args[])
{
new ServerTest().startServer();
}
/**
* 开启WEB服务
*
*/
public void startServer()
{
try
{
//获取配置信息,并进行初始化
getServerInfo();
server = new ServerSocket(PORT);
info("服务器开启,在"+PORT+"端口提供服务!");
//无限监听用户请求
while (true)
{
Socket client = server.accept();
//每连接一个客户,都构造一个内部类ServerThread,然后运行
new ServerThread(client).start();
}
} catch (IOException ioe)
{
sysError("建立服务时发生IO错误:"+ioe.getMessage());
} catch (Exception e)
{
e.printStackTrace();
sysError("发生非预见性错误,无法启动服务:"+e.getMessage());
}
}
public void stopServer()
{
try
{
if(this.server!=null)
server.close();
info("服务器关闭");
} catch (Exception e)
{
info("无法关闭服务:"+e.getMessage()+",将会强制退出系统");
System.exit(0);
}
}
/**
* 读取文件
* 获取服务路径
* 并对日志文件进行初始化
*/
private void getServerInfo()
{
try
{
//获取当前路径
File nowdir=new File(".").getAbsoluteFile();
String dirString=nowdir.toString();
String subs=dirString.substring(0,dirString.length()-1);
File fileInfo=new File(subs+"info/");
if(!fileInfo.exists()) fileInfo.mkdir();
//打开记录客户服务的日志文件
File logFile=new File(fileInfo,"server.log");
infoLog=new RandomAccessFile(logFile,"rw");
infoLog.seek(infoLog.length());
//打开记录错误信息的日志文件
File errorFile=new File(fileInfo,"error.log");
errorLog=new RandomAccessFile(errorFile,"rw");
errorLog.seek(errorLog.length());
//获取服务路径
File serverInfo=new File(fileInfo,"info.ini");
FileReader fr=new FileReader(serverInfo);
BufferedReader br=new BufferedReader(fr);
serverPath=br.readLine();
if((serverPath==null)||serverPath.trim().equals(""))
serverPath=nowdir.toString();//默认为当前路径
fr.close();
br.close();
}
catch(FileNotFoundException fnfe)
{
sysError("无法找到文件:"+fnfe.getMessage());
}
catch(IOException ioe)
{
sysError("打开文件过程中发生IO错误:"+ioe.getMessage());
}
catch(Exception e)
{
sysError("非预知错误:"+e.getMessage());
}
}
/**
* 记录服务信息
*
* @param info
*/
private void info(String info)
{
try
{
if(infoLog!=null)
{
Date today = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("20yy:MM:dd hh:mm: ");
String dateString = formatter.format(today);
if(taInfo!=null) taInfo.append((dateString+info)+"\n");
infoLog.write((dateString+info).getBytes());
infoLog.writeByte(13);
infoLog.writeByte(10);
}
}catch(Exception e)
{
e.printStackTrace();
}
}
/**
* 一般性错误
* 提供错误日志记录
* @param errorInfo
*/
private synchronized void error(String errorInfo)
{
try
{
if(errorLog!=null)
{
Date today = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("20yy:MM:dd hh:mm: ");
String dateString = formatter.format(today);
if(taInfo!=null) taInfo.append((dateString+errorInfo)+"\n");
String s=(dateString+":"+errorInfo);
errorLog.write(s.getBytes());
errorLog.writeByte(13);
errorLog.writeByte(10);
}
}catch(Exception e)
{
e.printStackTrace();
}
}
/**
* 严重错误
* 提供错误日志记录
* 发生该类错误后出现提示信息
* 然后退出服务器
* @param errorInfo
*/
private synchronized void sysError(String errorInfo)
{
String s=errorInfo+" ->服务器将会退出运行!";
error(errorInfo);
if(this.parentComponent!=null)
JOptionPane.showMessageDialog(this.parentComponent,s);
System.exit(0);
}
public JComponent getParentComponent()
{
return parentComponent;
}
public void setParentComponent(JComponent parentComponent)
{
this.parentComponent = parentComponent;
}
public String getServerPath()
{
return serverPath;
}
public void setServerPath(String serverPath)
{
this.serverPath = serverPath;
}
public JTextArea getTaInfo()
{
return taInfo;
}
public void setTaInfo(JTextArea taInfo)
{
this.taInfo = taInfo;
}
public int getUserNumber()
{
return userNumber;
}
/**
* 单独为每个一个用户打开一个线程 处理每个用户的请求服务
*/
class ServerThread extends Thread
{
/**
* 连接Web浏览器的socket
*/
Socket client;
/**
* 消息类型
*/
int messagesType=200;
/**
* 目的IP地址
*/
String destIP = null;
/**
* 客户机端口号
*/
int destport =80 ;
public ServerThread(Socket client)
{
this.client = client;
destIP= client.getInetAddress().toString();
destport=client.getPort();
}
public void run()//线程体
{
try
{
PrintStream outstream = new PrintStream(client.getOutputStream());
DataInputStream instream = new DataInputStream(client
.getInputStream());
String inline = instream.readLine();
//读取Web浏览器提交的请求信息
System.out.println("Received:" + inline);
if (getrequest(inline))
{//如果是GET请求
String filename = getRequestFileName(inline);
File file = new File(serverPath,filename);
System.out.println(file.toString());
//TODO
if (file.exists())
{
//若文件存在,则将文件送给Web浏览器
System.out.println(filename + "requested.");
outstream.println("HTTP/1.0 200 OK");
outstream.println("MIME_version:1.0");
outstream.println("Content_Type:text/htm1");
int len = (int) file.length();
outstream.println("Content_Length:" + len);
outstream.println("");
sendfile(outstream, file);//发送文件
outstream.flush();
} else
{//文件不存在时
String notfound = "htmlheadtitle Not Found/title/head bodyhlError404-File notfound /hl/body/html";
outstream.println("HTTP /1.0 404 no found");
outstream.println("Content_Type:text /html");
outstream.println("Content_Length:" + notfound.length() + 2);
outstream.println("");
outstream.println(notfound);
outstream.flush();
}
}
long m1 = 1;
while (m1 < 11100000)
{
m1++;
} // 延时
client.close();
} catch (IOException e)
{
System.out.println("Exception:" + e);
}
}
/*
* 获取请求类型是否为GET
*/
boolean getrequest(String s)
{
info("客户 "+this.destIP+"请求文件"+s);
if (s.length() > 0)
{
if (s.substring(0, 3).equalsIgnoreCase("GET"))
return true;
}
return false;
}
/*
* 获取要访问的文件名
*/
String getRequestFileName(String s)
{
String f = s.substring(s.indexOf('/') + 1);
try
{
int len=f.indexOf(' ');
if (f.charAt(0) == '/')
f = f.substring(1);
if(len!=-1)
f=f.substring(0,len);
} catch (IndexOutOfBoundsException e)
{
error("无法从字符串"+s+"中获取文件名.");
}
if (f.equals(""))
f = "index.html";
System.out.println("\nlabel:"+f+"\n");
return f;
}
/*
* 把指定文件发送给Web浏览器
*/
void sendfile(PrintStream outs, File file)
{
try
{
DataInputStream in = new DataInputStream(new FileInputStream(file));
int len = (int) file.length();
byte buf[] = new byte[len];
in.readFully(buf);
outs.write(buf, 0, len);
outs.flush();
in.close();
info("客户 "+this.destIP+"请求文件"+file+"成功!");
}
catch (IOException e)
{
error("发送文件"+file+"给客户"+this.destIP+"发生错误错误.");
// System.exit(1);
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -