MY PAGE
HELLO WORLD
server.java(服务器端)
public class Server {
public static void main(String[] args) {
ServerSocket server = null;
Socket socket = null;
String basePath = "E:\\webapps";
try {
server = new ServerSocket(8080);
System.out.println("服务器已启动....");
while(true){
socket = server.accept();
service(socket.getInputStream(), socket.getOutputStream(), basePath);
}
} catch (IOException e) {
e.printStackTrace();
}
}
//"/hello/index.html"
//提供服务的方法
private static void service(InputStream in,
OutputStream out, String basePath) throws IOException {
//读取本地index.html文件的流对象
BufferedReader br = null;
try{
//1- 接收并解析客户端发来的请求信息
int len = in.available();
byte[] buffer = new byte[len];
in.read(buffer);//以上三行,得到客户端的请求信息
String request = new String(buffer);
//2- 得到客户端想要的文件路径,从本地文件系统,读取该文件
File reqFile = new File(basePath, request);
// if(!reqFile.exists()){//判断请求文件是否存在。
// return;
// }
//3- 将读取的信息,发送给客户端
br = new BufferedReader(new FileReader(reqFile));
//边读取index.html文件,边向客户端发送。
String line = null;
while((line = br.readLine()) != null){
out.write((line + "\r\n").getBytes());
}
}catch(FileNotFoundException e){
out.write("404".getBytes());
out.flush();
}finally{
if(out != null){
out.close();
}
if(in != null){
in.close();
}
if(br != null){
br.close();
}
}
}
}
Client.java(客户端)
public class Client {
public static void main(String[] args) {
Socket client = null;
try {
//1- 连接服务器
client = new Socket("127.0.0.1", 8080);
//2- 向服务器发送请求信息
OutputStream out = client.getOutputStream();
out.write("\\hello\\index.html".getBytes());
out.flush();//刷新给服务器端文件路径
Thread.sleep(1000);//此处休眠很重要
//3- 接收服务器发送的信息,并打印输出到控制台
InputStream in = client.getInputStream();
// int len = in.available();
byte[] buffer = new byte[1024];
int len = -1;
while((len = in.read(buffer)) != -1){
System.out.println(new String(buffer, 0, len));
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(client != null){
try {
client.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
Web服务器是由专门的服务器开发商开发。对于Web而言,除了需要Web服务器,还需要 JSP/Servlet容器(Web服务器)。JSP/Servelt容器基本功能,把动态资源转换成静态资源。通常web服务器和JSP/Servlet容器集于一身。
MIME(Multipurpose Internet Mail Extension)多用途的网络邮件扩展协议。HTTP协议中请求正文和响应正文都可以看做是邮件。MIME规定了邮件标准格式,只要遵守MIME协议的数据类型,都统称为MIME类型。让接收方看得懂发送方发送的邮件。text/html; Content-type: text/html
<Host name="www.hao.com" appBase="c:\haoapps"
unpackWARs="true" autoDeploy="true">
Host>