• Socket编程


    服务器端:

    package server;
    import java.io.*;
    import java.net.*;

    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("端口号默认为:8080");
       port = 8080;
      }
      try {
       serverSocket = new ServerSocket(port);
       System.out.println("服务器正在监听端口" + serverSocket.getLocalPort());
       try {
        // 建立端口号等待tcp连接,侦听并接受到此套接字的连接。
        final Socket socket = serverSocket.accept();
        // 相应请求
        service(socket);
       } catch (Exception e) {
        // TODO: handle exception
       }
      } catch (Exception e) {

      }
     }

     public static void service(Socket socket) throws Exception {
      // TODO Auto-generated method stub
      // socket返回此套接字的输入流
      InputStream socketInput = socket.getInputStream();
      Thread.sleep(500);
      // 可以不受阻塞地从此输入流读取(或跳过)的估计字节数
      int size = socketInput.available();
      // 分配缓冲区
      byte[] buffer = new byte[size];
      // while(socketInput.read(buffer)!=-1){
      //   
      // }
      socketInput.read(buffer);
      String request = new String(buffer);
      // 将请求报文打出来
      System.out.println(request.toString());
      // 解析请求报文
      // 获取http报文第一行信息
      String firstLineOfRequset = request.substring(0, request
        .indexOf(" "));
      // 解析请求的第一行
      String[] parts = firstLineOfRequset.split(" ");
      String uri = parts[1];

      String contentType;
      if (uri.indexOf("html") != -1 || uri.indexOf("htm") != -1) {
       contentType = "text/html";
      } else if (uri.indexOf("jpg") != -1 || uri.indexOf("jpeg") != -1) {
       contentType = "image/jpeg";
      } else if (uri.indexOf("gif") != -1) {
       contentType = "image/gif";
      } else {
       contentType = "application/octet-stream";
      }

      // 创建响应结果
      // http响应第一行
      String reponseFirstLine = "HTTP/1.1 200 OK ";
      // 相应头
      String reponseHeader = "Content-Type:" + contentType + " ";
      // 获取读取响应正文数据的输入流
      InputStream in = HttpServer.class.getResourceAsStream("root/" + uri);

      // 发出Http响应结果
      OutputStream socketOut = socket.getOutputStream();

      // 发出报文的第一行:
      socketOut.write(reponseFirstLine.getBytes());
      // 发出相应头
      socketOut.write(reponseHeader.getBytes());
      // 发出相应正文
      int len = 0;
      buffer = new byte[128];
      while ((len = in.read(buffer)) != -1) {
       socketOut.write(buffer, 0, len);
      }
      Thread.sleep(1000);
      socket.close();
     }
    }

    客户端:

    package client;

    import java.io.*;
    import java.net.*;
    public class HttpClient {
     public static void main(String[] args) {
      String uri = "index.htm";
      if(args.length!=0) uri=args[0];
      doGet("localhost",8080,uri);//按照GET请求方式访问httpServer
     }

     public static void doGet(String host, int port, String uri) {
      Socket socket = null;
      try{
       //创建tcp链接
       socket = new Socket(host,port);
      }catch (Exception e) {
      }
      try{
       //创建请求
       StringBuffer sb = new StringBuffer("GET"+" hello1.htm"+" HTTP/1.1 ");//请求第一行
       //请求头
       sb.append("Accept: */* ");
       sb.append("Accept-Language: zh-cn ");
       sb.append("Accept-Encoding: gzip, deflate ");
       sb.append("User-Agent: HTTPCLient ");
       sb.append("Host-: localhost:8080 ");
       sb.append("Connecttion-: keep-Alive ");
       
       //发送HTTP请求
       OutputStream socketOut=socket.getOutputStream();
       socketOut.write(sb.toString().getBytes());
       
       Thread.sleep(2000);
       
       InputStream socketIn=socket.getInputStream();
       
       int size =socketIn.available();
       byte[] buffer=new byte[size];
       socketIn.read(buffer);
       System.out.println(new String(buffer));
       socket.close();
      }catch (Exception e) {
      }
     }
    }

    初步了解一下http传递报文的格式,和服务器端解析报文的模式。接下来会慢慢更新关于学习web和tomcat的东西。

  • 相关阅读:
    nginx源代码分析--监听套接字的创建 套接字的监听 HTTP请求创建连接
    JSP中Session的使用
    令人作呕的OpenSSL
    bottle的几个小坑
    UVA 11997
    Rational Rose 2007 &Rational Rose 2003 下载及破解方法和汉化文件下载
    MyEclipse下XFire开发Webservice实例
    OpenTSDB设计解读
    Spring整合Hibernate的步骤
    linux服务之audit
  • 原文地址:https://www.cnblogs.com/hdsbk/p/3518367.html
Copyright © 2020-2023  润新知