Socket实现简单的浏览器请求应答
Socket是对TCP/IP协议的封装形成的API,通过Socket,可以实现客户端和服务端的请求应答。我们常用的Servlet,也是将Socket进行再封装最后形成的。
以下代码是一个简单的实现:
public class SocketTest extends Thread{
private ServerSocket socket;
public SocketTest(int port) throws IOException {
socket = new ServerSocket(port);
socket.setSoTimeout(200000);
}
@Override
public void run() {
while(true) {
PrintWriter out = null;
Socket so = null;
BufferedReader reader = null;
try{
System.out.println("wait connection: " + socket.getLocalPort());
so = socket.accept();
reader = new BufferedReader(new InputStreamReader(so.getInputStream()));
out = new PrintWriter(
new OutputStreamWriter(so.getOutputStream(), "UTF-8"));
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<meta charset=\"UTF-8\">");
out.println("<title>Insert title here</title>");
out.println("</head>");
out.println("<body>");
out.println(" <p>欢迎</p> ");
out.println("</body>");
out.println("</html>");
out.flush();
String len = "";
while((len = reader.readLine()) != null) {
System.out.println(len);
if(StringUtils.isEmpty(len)) {
break;
}
}
System.out.println("end");
}
catch (IOException e) {
e.printStackTrace();
}
finally{
out.close();
try {
reader.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
so.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
try {
SocketTest tt = new SocketTest(9000);
tt.run();
} catch (Exception e) {
e.printStackTrace();
}
}
}
socket = new ServerSocket(port);是实现了服务端的socket对象,传入端口号,并设置了超时时间。so = socket.accept();是接受到的客户端的请求,通过so.getOutputStream()可以获取到客户端传入的参数:
GET /favicon.ico HTTP/1.1
Host: localhost:9000
Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36
Accept: /
Referer: http://localhost:9000/xprenc/hello.html
Accept-Encoding: gzip, deflate, sdch
Accept-Language: zh-CN,zh;q=0.8
通过outputstream可以将响应传递给浏览器,并最终显示到页面上。