package com.smtscript.lib.socket; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.smtscript.lib.JSStaticSocket; import com.smtscript.utils.SMTStatic; public class JSClientSocket { protected JSStaticSocket _parentSocket; protected Socket _clientSocket; protected static Pattern _patReqHead = Pattern.compile("^([^:]+):(.+)"); protected static Pattern _patReqFirst = Pattern.compile("^(GET|POST)\\s+([^\\s\\?]+)(?:\\?([^\\s]+))?(?:\\s+(HTTP/\\d+\\.\\d+))?"); public JSClientSocket(JSStaticSocket parentSocket, Socket clientSocket) { _parentSocket = parentSocket; _clientSocket = clientSocket == null ? new Socket() : clientSocket; } public void close() throws IOException { _clientSocket.close(); } protected String receiveLine(InputStream reader) throws Exception { int ch; byte[] buf = new byte[1024 * 100]; int len = 0; while((ch = reader.read()) != -1) { if(ch == '\r') continue; if(ch == '\n') break; buf[len ++] = (byte) ch; if(len >= buf.length) throw new Exception("head line to long"); } return new String(buf, 0, len); } public JSSocketHttpRequest receiveHttpRequest() throws Exception { JSSocketHttpRequest request = new JSSocketHttpRequest(); InputStream reader = _clientSocket.getInputStream(); // 读取第一行请求 String line = receiveLine(reader); Matcher m = _patReqFirst.matcher(line); if(m == null) throw new Exception("can't parse request first line : " + line); request._method = m.group(1); request._urlPath = m.group(2); request._urlParams = m.group(3); request._urlTail = m.group(4); // 读取后续参数行 while(!SMTStatic.isNullOrEmpty((line = receiveLine(reader)))) { m = _patReqHead.matcher(line); if(!m.find()) throw new Exception("can't parse request head line : " + line); request._Name2Head.put(m.group(1).toLowerCase(), new String[]{m.group(1), m.group(2)}); } // 尝试获取数据 String[] bodySize = request._Name2Head.get("content-length"); if(bodySize == null) { } // 解析request body return request; } }