欢迎光临
我们一直在努力

Java的网络编程:用Java实现Web服务器-JSP教程,Java技巧及代码

建站超值云服务器,限时71元/月

超文本传输协议(http)是位于tcp/ip 协议的应用层,是最广为人知的协议,也是互连网中最核心的协议之一,同样,http 也是基于 c/s 或 b/s 模型实现的。事实上,我们使用的浏览器如netscape 或ie 是实现http 协议中的客户端,而一些常用的web 服务器软件如apache、iis 和iplanet web server 等是实现http 协议中的服务器端。web 页由服务端资源定位,传输到浏览器,经过浏览器的解释后,被客户所看到。

web 的工作基于客户机/服务器计算模型,由web 浏览器(客户机)和web服务器(服务器)构成,两者之间采用超文本传送协议(http)进行通信。http协议是web浏览器和web服务器之间的应用层协议,是通用的、无状态的、面向对象的协议。

一个完整的http协议会话过程包括四个步骤:

◆ 连接,web浏览器与web服务器建立连接,打开一个称为socket(套接字)的虚拟文件,此文件的建立标志着连接建立成功;

◆ 请求,web浏览器通过socket向web服务器提交请求。http的请求一般是get或post命令(post用于form参数的传递);

◆ 应答,web浏览器提交请求后,通过http协议传送给web服务器。web服务器接到后,进行事务处理,处理结果又通过http传回给web浏览器,从而在web浏览器上显示出所请求的页面;

◆ 关闭连接,应答结束后web浏览器与web服务器必须断开,以保证其它web浏览器能够与web服务器建立连接。

java实现web服务器功能的程序设计

编程思路

根据上述http协议的会话过程,本实例中实现了get请求的web服务器程序的方法,方法如下:

通过创建serversocket 类对象,侦听用户指定的端口(为8080),等待并接受客户机请求到端口。创建与socket相关联的输入流和输出流,然后读取客户机的请求信息。若请求类型是get,则从请求信息中获取所访问的html 文件名;如果html 文件存在,则打开html 文件,把http 头信息和html 文件内容通过socket 传回给web浏览器,然后关闭文件,否则发送错误信息给web 浏览器。最后关闭与相应web 浏览器连接的socket。

用java编写web服务器httpserver.java文件的源代码如下:

//httpserver.java

import java.net.*;

import java.io.*;

import java.util.*;

import java.lang.*;

public class httpserver{

public static void main(string args[]) {

int port;

serversocket server_socket;

//读取服务器端口号

try {

port = integer.parseint(args[0]);

}

catch (exception e) {

port = 8080;

}

try {

//监听服务器端口,等待连接请求

server_socket = new serversocket(port);

system.out.println("httpserver running on port " +

server_socket.getlocalport());

//显示启动信息

while(true) {

socket socket = server_socket.accept();

system.out.println("new connection accepted " +

socket.getinetaddress() +

":" + socket.getport());

//创建分线程

try {

httprequesthandler request =

new httprequesthandler(socket);

thread thread = new thread(request);

//启动线程

thread.start();

}

catch(exception e) {

system.out.println(e);

}

}

}

catch (ioexception e) {

system.out.println(e);

}

}

}

class httprequesthandler implements runnable

{

final static string crlf = "\r\n";

socket socket;

inputstream input;

outputstream output;

bufferedreader br;

// 构造方法

public httprequesthandler(socket socket) throws exception

{

this.socket = socket;

this.input = socket.getinputstream();

this.output = socket.getoutputstream();

this.br =

new bufferedreader(new inputstreamreader(socket.getinputstream()));

}

// 实现runnable 接口的run()方法

public void run()

{

try {

processrequest();

}

catch(exception e) {

system.out.println(e);

}

}

private void processrequest() throws exception

{

while(true) {

//读取并显示web 浏览器提交的请求信息

string headerline = br.readline();

system.out.println("the client request is "+headerline);

if(headerline.equals(crlf) || headerline.equals("")) break;

stringtokenizer s = new stringtokenizer(headerline);

string temp = s.nexttoken();

if(temp.equals("get")) {

string filename = s.nexttoken();

filename = "." + filename ;

// 打开所请求的文件

fileinputstream fis = null ;

boolean fileexists = true ;

try

{

fis = new fileinputstream( filename ) ;

}

catch ( filenotfoundexception e )

{

fileexists = false ;

}

// 完成回应消息

string serverline = "server: a simple java httpserver";

string statusline = null;

string contenttypeline = null;

string entitybody = null;

string contentlengthline = "error";

if ( fileexists )

{

statusline = "http/1.0 200 ok" + crlf ;

contenttypeline = "content-type: " +

contenttype( filename ) + crlf ;

contentlengthline = "content-length: "

+ (new integer(fis.available())).tostring()

+ crlf;

}

else

{

statusline = "http/1.0 404 not found" + crlf ;

contenttypeline = "text/html" ;

entitybody = "<html>" +

"<head><title>404 not found</title></head>" +

"<body>404 not found"

+"<br>usage:http://yourhostname:port/"

+"filename.html</body></html>" ;

}

// 发送到服务器信息

output.write(statusline.getbytes());

output.write(serverline.getbytes());

output.write(contenttypeline.getbytes());

output.write(contentlengthline.getbytes());

output.write(crlf.getbytes());

// 发送信息内容

if (fileexists)

{

sendbytes(fis, output) ;

fis.close();

}

else

{

output.write(entitybody.getbytes());

}

}

}

//关闭套接字和流

try {

output.close();

br.close();

socket.close();

}

catch(exception e) {}

}

private static void sendbytes(fileinputstream fis, outputstream os)

throws exception

{

// 创建一个 1k buffer

byte[] buffer = new byte[1024] ;

int bytes = 0 ;

// 将文件输出到套接字输出流中

while ((bytes = fis.read(buffer)) != -1 )

{

os.write(buffer, 0, bytes);

}

}

private static string contenttype(string filename)

{

if (filename.endswith(".htm") || filename.endswith(".html"))

{

return "text/html";

}

return "filename";

}

}

编程技巧说明

◆ 主线程设计

主线程的设计就是在主线程httpserver 类中实现了服务器端口的侦听,服务器接受一个客户端请求之后创建一个线程实例处理请求,代码如下:

import java.net.*;

import java.io.*;

import java.util.*;

import java.lang.*;

public class httpserver{

public static void main(string args[]) {

port;

serversocket server_socket;

//读取服务器端口号

try {

port = integer.parseint(args[0]);

}

catch (exception e) {

port = 8080;

}

try {

//监听服务器端口,等待连接请求

server_socket = new serversocket(port);

system.out.println("httpserver running on port "

+server_socket.getlocalport());

……….

……….

◆ 连接处理分线程设计

在分线程httprequesthandler 类中实现了http 协议的处理,这个类实现了runnable 接口,代码如下:

class httprequesthandler implements runnable

{

final static string crlf = "\r\n";

socket socket;

inputstream input;

outputstream output;

bufferedreader br;

// 构造方法

public httprequesthandler(socket socket) throws exception

{

this.socket = socket;

//得到输入输出流

this.input = socket.getinputstream();

this.output = socket.getoutputstream();

this.br =

new bufferedreader(new inputstreamreader(socket.getinputstream()));

}

// 实现runnable 接口的run()方法

public void run()

{

try {

processrequest();

}

catch(exception e) {

system.out.println(e);

}

}

◆ 构建processrequest()方法来处理信息的接收和发送

作为实现runnable 接口的主要内容,在run()方法中调用processrequest()方法来处理客户请求内容的接收和服务器返回信息的发送,代码如下:

private void processrequest() throws exception

{

while(true) {

//读取并显示web 浏览器提交的请求信息

string headerline = br.readline();

system.out.println("the client request is "+ headerline);

if(headerline.equals(crlf) || headerline.equals("")) break;

//根据请求字符串中的空格拆分客户请求

stringtokenizer s = new stringtokenizer(headerline);

string temp = s.nexttoken();

if(temp.equals("get")) {

string filename = s.nexttoken();

filename = "." + filename ;

………….

………….

在processrequest()方法中得到客户端请求后,利用一个stringtokenizer 类完成了字符串的拆分,这个类可以实现根据字符串中指定的分隔符(缺省为空格)将字符串拆分成为字串的功能。利用nexttoken()方法依次得到这些字串;sendbytes()方法完成信息内容的发送,contenttype()方法用于判断文件的类型。

显示web页面

显示 web 页面的index.html 文件代码如下:

<html>

<head>

<meta http-equiv="content-language" content="zh-cn">

<meta name="generator" content="microsoft frontpage 5.0">

<meta http-equiv="content-type" content="text/html; charset=gb2312">

<title>java web 服务器</title>

</head>

<body>

<p>********* <font color="#ff0000">欢迎你的到来!</font>*********</p>

<p>这是一个用 java 语言实现的 web 服务器</p>

<hr>

</body>

</html>

运行实例

为了测试上述程序的正确性,将编译后的httpserver.class、httprequesthandler.class和上面的index.html文件置于网络的某台主机的同一目录中。

首先运行服务器程序 java httpserver 8080,服务器程序运行后显示端口信息“httpserver runing on port 8080”, 然后在浏览器的地址栏中输入http://localhost:8080/index.html,就可以正确显示网页,同时在显示“httpserver runing on port 8080 ”窗口中服务器会出现一些信息。

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » Java的网络编程:用Java实现Web服务器-JSP教程,Java技巧及代码
分享到: 更多 (0)

相关推荐

  • 暂无文章