您的位置:首页 > 理论基础 > 计算机网络

httpserver and client

2012-06-19 01:38 309 查看
package MyHttp;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.io.PrintStream;

import java.net.Socket;

import java.net.UnknownHostException;

public class MyHttpClient {

public static void main(String[] args) {

connecting();

}

private static void connecting() {

try {

Socket s=new Socket("www.baidu.com",80);

OutputStream out=s.getOutputStream();

InputStream in=s.getInputStream();

out.write("GET / HTTP/1.1\r\n".getBytes());

out.write("Host:
www.baidu.com\r\n".getBytes());

out.write("\r\n".getBytes());

ByteArrayOutputStream baos=new ByteArrayOutputStream();

for(int len,count=0;(len=in.read())!=-1;){

if(len==13){

continue;

}else if(len==10){

count++;

if(count==2){

break;

}

}else{

count=0;

}

baos.write(len);

}

byte[] bufs=baos.toByteArray();

String str=new String(bufs);

// System.out.println(str);

int beginIndex=str.indexOf("Content-Length: ")+16;

str=str.substring(beginIndex,str.indexOf("\n",beginIndex));

int bodyLen=Integer.parseInt(str);

int total=0;

byte[] buf=new byte[bodyLen];

do{

int len=in.read(buf,0,buf.length-total);

total+=len;

System.out.println(new String(buf,0,len));

}while(total<buf.length);

in.close();

s.close();

} catch (UnknownHostException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

private static void copyStream(InputStream in, OutputStream out) throws IOException {

byte[] bufs=new byte[1024];

for(int len;(len=in.read())!=-1;){

out.write(bufs, 0, len);

}

}

}

package MyHttp;

import java.io.BufferedReader;

import java.io.ByteArrayOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.ServerSocket;

import java.net.Socket;

import java.util.Properties;

public class MyHttpServer {

public static void main(String[] args) {

startHttpServer();

}

private static void startHttpServer() {

try {

ServerSocket ss=new ServerSocket(8888);

System.out.println("Http Server starting on port 8888");

while(true){

Socket s=ss.accept();

System.out.println("客服端"+s.getInetAddress().getHostAddress()+"已通过"+s.getPort()+

"端口连接进来");

new MyHttpServer().new Working(s);

}

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

private class Working implements Runnable{

Socket s=null;

public Working(Socket s){

this.s=s;

new Thread(this).start();

}

@Override

public void run(){

try {

boolean flag=true;

InputStream in=null;

OutputStream out=null;

BufferedReader br=null;

InputStream Ips=null;

ByteArrayOutputStream baos=new ByteArrayOutputStream();

in=s.getInputStream();

out=s.getOutputStream();

while(flag){

//获取消息头的第一行

String requestLine="";

for(int len;(len=in.read())!=-1;){

if(len==13){

continue;

}else if(len==10){

break;

}

requestLine+=(char)len;

}

//根据消息头的第一行进行判断客服端的提交是否合法

if(requestLine==null){

flag=false;

break;

}

String[] requestFields=requestLine.split(" +");

if(requestFields.length!=3){

out.write("协议头出错".getBytes());

flag=false;

break;

}

if(!requestFields[2].startsWith("HTTP/")){

out.write("只支持HTTP协议\n".getBytes());

flag=false;

break;

}

//合法的情况下打印消息头

System.out.println(requestLine);

for(int len,count=0;(len=in.read())!=-1;){

if(len==13){

continue;

}else if(len==10){

count++;

if(count==2){

break;

}

}else{

count=0;

}

baos.write(len);

}

String requestHead=new String(baos.toByteArray());

System.out.println(requestHead);

if(requestFields[0].equals("POST")){

int beginIndex =requestHead.indexOf("Content-Length:")+15;

int endIndex=requestHead.indexOf("\n",beginIndex);

int bodyLen=0;

if(beginIndex!=endIndex){

String lenStr=requestHead.substring(beginIndex, endIndex);

bodyLen=Integer.parseInt(lenStr.trim());

}

byte[] bufs=new byte[bodyLen];

int len=in.read(bufs);

System.out.println(new String(bufs,0,len));

out.write((("HTTP/1.1 2OO OK\r\nContent_Length: 30\r\n\r\n")).getBytes());

out.write("Welcome to my Server".getBytes());

break;

}else if(requestFields[0].equals("GET")){

String filePath=requestFields[1];

Properties properties=new Properties();

Ips=this.getClass().getResourceAsStream("Resource/vfs.property");

properties.load(Ips);

String root="";

File dir=null;

if(filePath.indexOf("/",1)>0){

root=filePath.substring(0,filePath.indexOf("/",1));

if(properties.getProperty(root)!=null){

dir=new File(properties.getProperty(root));

if(dir.isDirectory()){

if(filePath.indexOf("/",1)==filePath.length()-1){

filePath="//index.html";

}

File file=new File(dir.getAbsolutePath()+filePath.substring(filePath.indexOf("/",1)));

if(!file.isFile()){

file=new File("bin/MyHttp/Resource/404");

}

writeFile(out,file);

break;

}

}

}

root=properties.getProperty("/");

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

filePath="/index.html";

}

File file=new File(root+"/"+filePath);

if(!file.isFile()){

file=new File("bin/MyHttp/Resource/404");

}

writeFile(out,file);

flag=false;

}else{

out.write("不支持POST和GET以外的模式".getBytes());

}

}

if(Ips!=null){

Ips.close();

}

in.close();

out.close();

s.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

private void writeFile(OutputStream out, File file)

throws FileNotFoundException, IOException {

System.out.println("开始传输文件");

InputStream fis=new FileInputStream(file);

out.write((("HTTP/1.1 2OO OK\nContent_Length: "+file.length())+"\n\n").getBytes());

copyStream(fis,out,false);

}

}

public static void copyStream(InputStream in,OutputStream out,boolean isClose){

byte[] bufs=new byte[1024];

try {

for(int len;(len=in.read(bufs))!=-1;){

out.write(bufs,0,len);

}

if(isClose){

in.close();

out.close();

}

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: