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("\r\n"));
  // 解析请求的第一行
  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\r\n";
  // 相应头
  String reponseHeader = "Content-Type:" + contentType + "\r\n\r\n";
  // 获取读取响应正文数据的输入流
  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\r\n");//请求第一行
   //请求头
   sb.append("Accept: */*\r\n");
   sb.append("Accept-Language: zh-cn\r\n");
   sb.append("Accept-Encoding: gzip, deflate\r\n");
   sb.append("User-Agent: HTTPCLient\r\n");
   sb.append("Host-: localhost:8080\r\n");
   sb.append("Connecttion-: keep-Alive\r\n\r\n");
   
   //发送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的东西。

Socket编程

上一篇:删除power by dedecms的方法


下一篇:类似微信下拉眼睛UI