1、HTTP server
接收client端的http请求并将同级目录的root/?返回
package httpDemo;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class HttpServer {
public static void main(String[] args) {
int port;
ServerSocket serverSocket;
try {
port=Integer.parseInt(args[0]);
} catch (Exception e) {
System.out.println("port=8080 (default)");
port=8080;
}
try {
serverSocket=new ServerSocket(port);
System.out.println("server is running on port:"+serverSocket.getLocalPort());
while (true) {
try {
final Socket socket=serverSocket.accept();
System.out.println("biuld a new tcp link with client,the cient address:"+
socket.getInetAddress()+":"+socket.getPort());
service(socket);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static void service(Socket socket)throws Exception{
//read http information
InputStream socketIn=socket.getInputStream();
Thread.sleep(500);
int size=socketIn.available();
byte[] buffer=new byte[size];
socketIn.read(buffer);
String request=new String(buffer);
System.out.println(request);
//
//get http request first line
String firstLineOfRequest=request.substring(0, request.indexOf("\r\n"));
String[] parts=firstLineOfRequest.split(" ");
String uri=parts[1];
//mime
String contentType;
if(uri.indexOf("html")!=-1||uri.indexOf("htm")!=-1)
contentType="text/html";
else {
contentType="application/octet-stream";
}
//create http response
//the first line
String responseFirstLine="HTTP/1.1 200 OK\r\n";
//http response head
String responseHeade="Content-Type:"+contentType+"\r\n";
//send http response result
OutputStream socketOut=socket.getOutputStream();
//send http response first line
socketOut.write(responseFirstLine.getBytes());
//send http response heade
socketOut.write(responseHeade.getBytes());
InputStream in=HttpServer.class.getResourceAsStream("root/"+uri);
//send content
socketOut.write("\r\n".getBytes());
int len=0;
buffer=new byte[128];
if (in!=null) {
while((len=in.read(buffer))!=-1){
System.out.println(new String(buffer));
socketOut.write(buffer,0,len);
}
}
Thread.sleep(1000);
//close tcp link
socket.close();
}
}
2、HTTP client
负责连接服务端socket并建立http连接发送请求
package httpDemo;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class HttpClient {
public static void main(String[] args) {
// forsure http request uri
String uri="index.htm";
if (args.length!=0) {
uri=args[0];
}
doGet("localhost",8080,uri);
}
private static void doGet(String host, int port, String uri) {
Socket socket=null;
try {
socket=new Socket(host,port);
} catch (Exception e) {
e.printStackTrace();
}
try {
StringBuffer sb=new StringBuffer("GET "+uri+" HTTP/1.1\r\n");
sb.append("Accept: */*\r\n");
sb.append("Accept-Language: zh-cn\r\n");
sb.append("User-Agent: HTTPClient\r\n");
sb.append("Host: localhost:8080\r\n");
sb.append("Connection: Keep-Alive\r\n");
//send http request
OutputStream socketOut=socket.getOutputStream();
socketOut.write(sb.toString().getBytes());
Thread.sleep(2000);//sleep 2s ,wait response
//recieve
InputStream socketIn=socket.getInputStream();
int size=socketIn.available();
byte[] buffer=new byte[size];
socketIn.read(buffer);
System.out.println(new String(buffer));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
当使用HTTPClient访问HTTPServer时候,server端控制台打印:
biuld a new tcp link with client,the cient address:/127.0.0.1:62722
GET index.htm HTTP/1.1
Accept: */*
Accept-Language: zh-cn
User-Agent: HTTPClient
Host: localhost:8080
Connection: Keep-Alive
<html>
<h1>oooooooooooopppppppppppppppppppp</h1>
</html>
client端打印:
biuld a new tcp link with client,the cient address:/127.0.0.1:62722
GET index.htm HTTP/1.1
Accept: */*
Accept-Language: zh-cn
User-Agent: HTTPClient
Host: localhost:8080
Connection: Keep-Alive
<html>
<h1>oooooooooooopppppppppppppppppppp</h1>
</html>
当使用火狐浏览器访问HTTPServer时候,server端控制台打印:
port=8080 (default)
server is running on port:8080
biuld a new tcp link with client,the cient address:/127.0.0.1:62351
GET /index.htm HTTP/1.1
Host: localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Cookie: JSESSIONID=7AF11CBE9CF2A52BE339FD670E706B61
Connection: keep-alive
Cache-Control: max-age=0
浏览器页码返回如下:
只要遵守相同的规则(HTTP),就能够互相交流。