600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > 代码实现-浏览器访问socket服务(简单)

代码实现-浏览器访问socket服务(简单)

时间:2020-02-18 07:09:02

相关推荐

代码实现-浏览器访问socket服务(简单)

前言

我们用过许多web服务器(Tomcat,Apache,WebLogic…)其实他们是功能很强大的socket服务,当我们在浏览器地址栏输入对应的IP地址,其实也就是浏览器创建了一个socket连接。那么服务端能否响应一段文字呢?

实现的功能

在浏览器地址栏输入:http://localhost:8888/index.html返回对应页面,如果没有就返回404,服务端用java编写的ServerSocket完成,并获取浏览器请求的内容。通过流,根据请求的路径,读取相应的html文件,并返回给浏览器。

实现代码

package com.test;import java.io.*;import .ServerSocket;import .Socket;/*** @Author: cxx* @Date: /6/20 15:20*/public class ServerTest {private static int port = 8888;private static Socket accept;private static ServerSocket socket;private static BufferedWriter bw;public static void main(String[] args) throws Exception {socket = new ServerSocket(port);System.out.println("服务器开启,等待连接....");while (true){accept = socket.accept();InputStreamReader r = new InputStreamReader(accept.getInputStream());System.out.println("浏览器请求成功!");BufferedReader br = new BufferedReader(r);String readLine = br.readLine();System.out.println("---------------------");//打印请求消息String filePath="log";int i=0;while(readLine != null && !readLine.equals("")){System.out.println(readLine);if (i==0){String[] split = readLine.split(" ");if (split[1].endsWith("html")) {filePath += split[1];}}i++;readLine=br.readLine();}System.out.println("----------------------");//发送响应请求System.out.println(filePath);writeHtml(filePath);}}public static void writeHtml(String filePath) throws Exception{if (!"log/index.html".equals(filePath)){filePath="log/404.html";}FileInputStream fis = new FileInputStream(filePath);int len=0;byte[] b = new byte[1024];StringBuilder sb = new StringBuilder();//拼装http响应的数据格式sb.append("http/1.1 200 ok").append("\n\n");while ((len=fis.read(b))!=-1){sb.append(new String(b,0,len));}bw = new BufferedWriter(new OutputStreamWriter(accept.getOutputStream()));bw.write(sb.toString());bw.flush();bw.close();}}

注意

浏览器每次发起请求,都会同时请求一次favicon.ico(本次不讨论浏览器缓存了favicon.ico)。

浏览器请求成功!---------------------GET /index.html HTTP/1.1Host: localhost:8888Connection: keep-aliveUpgrade-Insecure-Requests: 1User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8Accept-Encoding: gzip, deflate, brAccept-Language: zh-CN,zh;q=0.9----------------------log/index.html浏览器请求成功!---------------------GET /favicon.ico HTTP/1.1Host: localhost:8888Connection: keep-aliveUser-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36Accept: image/webp,image/apng,image/*,*/*;q=0.8Referer: http://localhost:8888/index.htmlAccept-Encoding: gzip, deflate, brAccept-Language: zh-CN,zh;q=0.9----------------------log浏览器请求成功!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。