Android 端的基于TCP的小型服务器_超级简单

服务端代码:
HttpServer:

package example.com.httpserver;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.util.Base64;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Locale;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.Vector;

/**
 * A simple, tiny, nicely embeddable HTTP 1.0 server in Java
 * Modified from NanoHTTPD, you can find it here
 * http://elonen.iki.fi/code/nanohttpd/
 */
public class HttpServer
{
	// ==================================================
	// API parts
	// ==================================================

	/**
	 * Override this to customize the server.<p>
	 *
	 * (By default, this delegates to serveFile() and allows directory listing.)
	 *
	 * @param uri	Percent-decoded URI without parameters, for example "/index.cgi"
	 * @param method	"GET", "POST" etc.
	 * @param parms	Parsed, percent decoded parameters from URI and, in case of POST, data.
	 * @param header	Header entries, percent decoded
	 * @return HTTP response, see class Response for details
	 */
	public Response serve( String uri, String method, Properties header, Properties parms, Properties files )
	{
		sPrintln( method + " '" + uri + "' " );

		Enumeration e = header.propertyNames();
		while ( e.hasMoreElements())
		{
			String value = (String)e.nextElement();
			sPrintln( "  HEADER: '" + value + "' = '" +
								header.getProperty( value ) + "'" );
		}
		e = parms.propertyNames();
		while ( e.hasMoreElements())
		{
			String value = (String)e.nextElement();
			sPrintln( "  PARMS: '" + value + "' = '" +
								parms.getProperty( value ) + "'" );
		}
		e = files.propertyNames();
		while ( e.hasMoreElements())
		{
			String value = (String)e.nextElement();
			sPrintln( "  UPLOADED: '" + value + "' = '" +
								files.getProperty( value ) + "'" );
		}

		int index = uri.indexOf("/", 1) + 1;
		String newUri = null;
		if (uri.startsWith("/path/")) {
			newUri = uri.substring(uri.lastIndexOf("/") + 1);
		}
		// http://192.168.0.116:9192/image/L3N0b3JhZ2UvZW11bGF0ZWQvMC9EQ0lNL0NhbWVyYS9JTUdfMjAyMDA0MTVfMTYwNjQ3.jpg
		//{"len":75,"use":"play","type":"video","url":"/storage/emulated/0/Pictures/Screenshots/Screenshot_2020-04-03-14-40-05.jpg"}
		//
        //
		// {"len":55,"use":"play","name":"VID_20200415_160655.mp4","type":"video","url":"/storage/emulated/0/DCIM/Camera/VID_20200415_160655.mp4"}
		if (uri.startsWith("/video/") || uri.startsWith("/music/") || uri.startsWith("/image/")) {
			try {
				int end = uri.lastIndexOf(".");
				end = end == -1 ? uri.length() : end;
				byte[] decode = Base64.decode(uri.substring(index, end), Base64.URL_SAFE);
				newUri = new String(decode, "UTF-8") + uri.substring(end);
				sPrintln("new Url=>" + newUri);
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}
		}
		return serveFile( newUri, header);
	}

	/**
	 * HTTP response.
	 * Return one of these from serve().
	 */
	public class Response
	{
		/**
		 * Default constructor: response = HTTP_OK, data = mime = 'null'
		 */
		public Response()
		{
			this.status = HTTP_OK;
		}

		/**
		 * Basic constructor.
		 */
		public Response( String status, String mimeType, InputStream data )
		{
			this.status = status;
			this.mimeType = mimeType;
			this.data = data;
		}

		/**
		 * Convenience method that makes an InputStream out of
		 * given text.
		 */
		public Response( String status, String mimeType, String txt )
		{
			this.status = status;
			this.mimeType = mimeType;
			try
			{
				this.data = new ByteArrayInputStream( txt.getBytes("UTF-8"));
			}
			catch ( java.io.UnsupportedEncodingException uee )
			{
				uee.printStackTrace();
			}
		}

		/**
		 * Adds given line to the header.
		 */
		public void addHeader( String name, String value )
		{
			header.put( name, value );
		}

		/**
		 * HTTP status code after processing, e.g. "200 OK", HTTP_OK
		 */
		public String status;

		/**
		 * MIME type of content, e.g. "text/html"
		 */
		public String mimeType;

		/**
		 * Data of the response, may be null.
		 */
		public InputStream data;

		/**
		 * Headers for the HTTP response. Use addHeader()
		 * to add lines.
		 */
		public Properties header = new Properties();
	}

	/**
	 * Some HTTP response status codes
	 */
	public static final String
		HTTP_OK = "200 OK",
		HTTP_PARTIALCONTENT = "206 Partial Content",
		HTTP_RANGE_NOT_SATISFIABLE = "416 Requested Range Not Satisfiable",
		HTTP_REDIRECT = "301 Moved Permanently",
		HTTP_FORBIDDEN = "403 Forbidden",
		HTTP_NOTFOUND = "404 Not Found",
		HTTP_BADREQUEST = "400 Bad Request",
		HTTP_INTERNALERROR = "500 Internal Server Error",
		HTTP_NOTIMPLEMENTED = "501 Not Implemented";

	/**
	 * Common mime types for dynamic content
	 */
	public static final String
		POST_DATA = "postData",
		MIME_PLAINTEXT = "text/plain",
		MIME_HTML = "text/html",
		MIME_DEFAULT_BINARY = "application/octet-stream",
		MIME_XML = "text/xml";

	// ==================================================
	// Socket & server code
	// ==================================================



	/**
	 * Starts a HTTP server to given port.<p>
	 * Throws an IOException if the socket is already in use
	 */
	private int mTcpPort;
	private IOnExitHandler mOnExitHandler;
	private boolean mIsStop;
	private HttpServer( int port ) throws IOException
	{
		mTcpPort = port;
		myServerSocket = new ServerSocket(mTcpPort);
		myThread = new Thread( new Runnable()
			{
				public void run()
				{
					IOException exception = null;
					try
					{
						while( !mIsStop ) {
							Socket socket = myServerSocket.accept();
							new HTTPSession(socket);
						}
					}
					catch ( IOException ioe )
					{
						exception = ioe;
						ioe.printStackTrace();
					}finally {
						if (!mIsStop && mOnExitHandler!=null) {
							mOnExitHandler.onExitHandler(exception);
						}
					}
				}
			});
		myThread.setDaemon( true );
		myThread.start();
	}

	public int getTcpPort() {
		return mTcpPort;
	}

	public void setOnExitHandler(IOnExitHandler onExitHandler) {
		mOnExitHandler = onExitHandler;
	}

	public interface IOnExitHandler{
		void onExitHandler(Throwable t);
	}

	public static final HttpServer safeStart() {
		int port = 9192;
		HttpServer httpServer = null;
		do {
			try {
				httpServer = new HttpServer(port);
			} catch (IOException e) {
				e.printStackTrace();
				port++;
			}
		} while (httpServer == null && port < 9195);
		return httpServer;
	}

	/**
	 * Stops the server.
	 */
	public void stop()
	{
		mIsStop = true;
		try
		{
			myServerSocket.close();
			myThread.join();
		}
		catch ( IOException ioe ) {}
		catch ( InterruptedException e ) {}
	}

	/**
	 * Handles one session, i.e. parses the HTTP request
	 * and returns the response.
	 */
	private class HTTPSession implements Runnable
	{
		public HTTPSession( Socket s )
		{
			mySocket = s;
			Thread t = new Thread( this );
			t.setDaemon( true );
			t.start();
		}

		public void run()
		{
			try
			{
				sPrintln("HTTPSession run start ThreadId=>" + Thread.currentThread().getId());
				InputStream is = mySocket.getInputStream();
				if ( is == null) return;

				// Read the first 8192 bytes.
				// The full header should fit in here.
				// Apache's default header limit is 8KB.
				int bufsize = 8192;
				byte[] buf = new byte[bufsize];
				int rlen = is.read(buf, 0, bufsize);
				if (rlen <= 0) return;

				// Create a BufferedReader for parsing the header.
				ByteArrayInputStream hbis = new ByteArrayInputStream(buf, 0, rlen);
				BufferedReader hin = new BufferedReader( new InputStreamReader( hbis ));
				Properties pre = new Properties();
				Properties parms = new Properties();
				Properties header = new Properties();
				Properties files = new Properties();

				// Decode the header into parms and header java properties
				decodeHeader(hin, pre, parms, header);
				String method = pre.getProperty("method");
				String uri = pre.getProperty("uri");
				Logger.d(Logger._JN, "method %s uri %s params: %s header: %s ", method,uri,parms,header);
				long size = 0x7FFFFFFFFFFFFFFFl;
				String contentLength = header.getProperty("content-length");
				if (contentLength != null)
				{
					try { size = Integer.parseInt(contentLength); }
					catch (NumberFormatException ex) {}
				}

				// We are looking for the byte separating header from body.
				// It must be the last byte of the first two sequential new lines.
				int splitbyte = 0;
				boolean sbfound = false;
				while (splitbyte < rlen)
				{
					if (buf[splitbyte] == '\r' && buf[++splitbyte] == '\n' && buf[++splitbyte] == '\r' && buf[++splitbyte] == '\n') {
						sbfound = true;
						break;
					}
					splitbyte++;
				}
				splitbyte++;

				// Write the part of body already read to ByteArrayOutputStream f
				ByteArrayOutputStream f = new ByteArrayOutputStream();
				if (splitbyte < rlen) f.write(buf, splitbyte, rlen-splitbyte);

				// While Firefox sends on the first read all the data fitting
				// our buffer, Chrome and Opera sends only the headers even if
				// there is data for the body. So we do some magic here to find
				// out whether we have already consumed part of body, if we
				// have reached the end of the data to be sent or we should
				// expect the first byte of the body at the next read.
				if (splitbyte < rlen)
					size -= rlen - splitbyte +1;
				else if (!sbfound || size == 0x7FFFFFFFFFFFFFFFl)
					size = 0;

				// Now read all the body and write it to f
				buf = new byte[512];
				while ( rlen >= 0 && size > 0 )
				{
					rlen = is.read(buf, 0, 512);
					size -= rlen;
					if (rlen > 0)
						f.write(buf, 0, rlen);
				}

				// Get the raw body as a byte []
				byte [] fbuf = f.toByteArray();

				// Create a BufferedReader for easily reading it as string.
				ByteArrayInputStream bin = new ByteArrayInputStream(fbuf);
				BufferedReader in = new BufferedReader( new InputStreamReader(bin));

				// If the method is POST, there may be parameters
				// in data section, too, read it:
				if ( method.equalsIgnoreCase( "POST" ))
				{
					String contentType = "";
					String contentTypeHeader = header.getProperty("content-type");
					StringTokenizer st = new StringTokenizer( contentTypeHeader , "; " );
					if ( st.hasMoreTokens()) {
						contentType = st.nextToken();
					}

					if (contentType.equalsIgnoreCase("multipart/form-data"))
					{
						// Handle multipart/form-data
						if ( !st.hasMoreTokens())
							sendError( HTTP_BADREQUEST, "BAD REQUEST: Content type is multipart/form-data but boundary missing. Usage: GET /example/file.html" );
						String boundaryExp = st.nextToken();
						st = new StringTokenizer( boundaryExp , "=" );
						if (st.countTokens() != 2)
							sendError( HTTP_BADREQUEST, "BAD REQUEST: Content type is multipart/form-data but boundary syntax error. Usage: GET /example/file.html" );
						st.nextToken();
						String boundary = st.nextToken();

						decodeMultipartData(boundary, fbuf, in, parms, files);
					}
					else
					{
						// Handle application/x-www-form-urlencoded
						String postLine = "";
						char pbuf[] = new char[512];
						int read = in.read(pbuf);
						while ( read >= 0 && !postLine.endsWith("\r\n") )
						{
							postLine += String.valueOf(pbuf, 0, read);
							read = in.read(pbuf);
						}
						postLine = postLine.trim();
						decodeParms( postLine, parms );
						if (parms.isEmpty() && postLine.length() > 0) {
							parms.put(POST_DATA, "postLine");
						}
					}
				}

				// Ok, now do the serve()
				Response r = serve( uri, method, header, parms, files );
				if ( r == null )
					sendError( HTTP_INTERNALERROR, "SERVER INTERNAL ERROR: Serve() returned a null response." );
				else
					sendResponse( r.status, r.mimeType, r.header, r.data );

				in.close();
				is.close();
			}
			catch ( IOException ioe )
			{
				try
				{
					sendError( HTTP_INTERNALERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
				}
				catch ( Throwable t ) {}
			}
			catch (Throwable ie )
			{
				ie.printStackTrace();
				// Thrown by sendError, ignore and exit the thread.
			}finally {
				sPrintln("HTTPSession run stop ThreadId=>" + Thread.currentThread().getId());
			}
		}

		/**
		 * Decodes the sent headers and loads the data into
		 * java Properties' key - value pairs
		**/
		private  void decodeHeader(BufferedReader in, Properties pre, Properties parms, Properties header)
			throws InterruptedException
		{
			try {
				// Read the request line
				String inLine = in.readLine();
				if (inLine == null) return;
				StringTokenizer st = new StringTokenizer( inLine );
				if ( !st.hasMoreTokens())
					sendError( HTTP_BADREQUEST, "BAD REQUEST: Syntax error. Usage: GET /example/file.html" );

				String method = st.nextToken();
				pre.put("method", method);

				if ( !st.hasMoreTokens())
					sendError( HTTP_BADREQUEST, "BAD REQUEST: Missing URI. Usage: GET /example/file.html" );

				String uri = st.nextToken();

				// Decode parameters from the URI
				int qmi = uri.indexOf( '?' );
				if ( qmi >= 0 )
				{
					decodeParms( uri.substring( qmi+1 ), parms );
					uri = decodePercent( uri.substring( 0, qmi ));
				}
				else uri = decodePercent(uri);

				// If there's another token, it's protocol version,
				// followed by HTTP headers. Ignore version but parse headers.
				// NOTE: this now forces header names lowercase since they are
				// case insensitive and vary by client.
				if ( st.hasMoreTokens())
				{
					String line = in.readLine();
					while ( line != null && line.trim().length() > 0 )
					{
						int p = line.indexOf( ':' );
						if ( p >= 0 )
							header.put( line.substring(0,p).trim().toLowerCase(), line.substring(p+1).trim());
						line = in.readLine();
					}
				}

				pre.put("uri", uri);
			}
			catch ( IOException ioe )
			{
				sendError( HTTP_INTERNALERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
			}
		}

		/**
		 * Decodes the Multipart Body data and put it
		 * into java Properties' key - value pairs.
		**/
		private void decodeMultipartData(String boundary, byte[] fbuf, BufferedReader in, Properties parms, Properties files)
			throws InterruptedException
		{
			try
			{
				int[] bpositions = getBoundaryPositions(fbuf,boundary.getBytes());
				int boundarycount = 1;
				String mpline = in.readLine();
				while ( mpline != null )
				{
					if (mpline.indexOf(boundary) == -1)
						sendError( HTTP_BADREQUEST, "BAD REQUEST: Content type is multipart/form-data but next chunk does not start with boundary. Usage: GET /example/file.html" );
					boundarycount++;
					Properties item = new Properties();
					mpline = in.readLine();
					while (mpline != null && mpline.trim().length() > 0)
					{
						int p = mpline.indexOf( ':' );
						if (p != -1)
							item.put( mpline.substring(0,p).trim().toLowerCase(), mpline.substring(p+1).trim());
						mpline = in.readLine();
					}
					if (mpline != null)
					{
						String contentDisposition = item.getProperty("content-disposition");
						if (contentDisposition == null)
						{
							sendError( HTTP_BADREQUEST, "BAD REQUEST: Content type is multipart/form-data but no content-disposition info found. Usage: GET /example/file.html" );
						}
						StringTokenizer st = new StringTokenizer( contentDisposition , "; " );
						Properties disposition = new Properties();
						while ( st.hasMoreTokens())
						{
							String token = st.nextToken();
							int p = token.indexOf( '=' );
							if (p!=-1)
								disposition.put( token.substring(0,p).trim().toLowerCase(), token.substring(p+1).trim());
						}
						String pname = disposition.getProperty("name");
						pname = pname.substring(1,pname.length()-1);

						String value = "";
						if (item.getProperty("content-type") == null) {
							while (mpline != null && mpline.indexOf(boundary) == -1)
							{
								mpline = in.readLine();
								if ( mpline != null)
								{
									int d = mpline.indexOf(boundary);
									if (d == -1)
										value+=mpline;
									else
										value+=mpline.substring(0,d-2);
								}
							}
						}
						else
						{
							if (boundarycount> bpositions.length)
								sendError( HTTP_INTERNALERROR, "Error processing request" );
							int offset = stripMultipartHeaders(fbuf, bpositions[boundarycount-2]);
							String path = saveTmpFile(fbuf, offset, bpositions[boundarycount-1]-offset-4);
							files.put(pname, path);
							value = disposition.getProperty("filename");
							value = value.substring(1,value.length()-1);
							do {
								mpline = in.readLine();
							} while (mpline != null && mpline.indexOf(boundary) == -1);
						}
						parms.put(pname, value);
					}
				}
			}
			catch ( IOException ioe )
			{
				sendError( HTTP_INTERNALERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
			}
		}

		/**
		 * Find the byte positions where multipart boundaries start.
		**/
		public int[] getBoundaryPositions(byte[] b, byte[] boundary)
		{
			int matchcount = 0;
			int matchbyte = -1;
			Vector matchbytes = new Vector();
			for (int i=0; i<b.length; i++)
			{
				if (b[i] == boundary[matchcount])
				{
					if (matchcount == 0)
						matchbyte = i;
					matchcount++;
					if (matchcount==boundary.length)
					{
						matchbytes.addElement(new Integer(matchbyte));
						matchcount = 0;
						matchbyte = -1;
					}
				}
				else
				{
					i -= matchcount;
					matchcount = 0;
					matchbyte = -1;
				}
			}
			int[] ret = new int[matchbytes.size()];
			for (int i=0; i < ret.length; i++)
			{
				ret[i] = ((Integer)matchbytes.elementAt(i)).intValue();
			}
			return ret;
		}

		/**
		 * Retrieves the content of a sent file and saves it
		 * to a temporary file.
		 * The full path to the saved file is returned.
		**/
		private String saveTmpFile(byte[] b, int offset, int len)
		{
			String path = "";
			if (len > 0)
			{
				String tmpdir = System.getProperty("java.io.tmpdir");
				try {
					File temp = File.createTempFile("NanoHTTPD", "", new File(tmpdir));
					OutputStream fstream = new FileOutputStream(temp);
					fstream.write(b, offset, len);
					fstream.close();
					path = temp.getAbsolutePath();
				} catch (Exception e) { // Catch exception if any
					System.err.println("Error: " + e.getMessage());
				}
			}
			return path;
		}


		/**
		 * It returns the offset separating multipart file headers
		 * from the file's data.
		**/
		private int stripMultipartHeaders(byte[] b, int offset)
		{
			int i = 0;
			for (i=offset; i<b.length; i++)
			{
				if (b[i] == '\r' && b[++i] == '\n' && b[++i] == '\r' && b[++i] == '\n')
					break;
			}
			return i+1;
		}

		/**
		 * Decodes the percent encoding scheme. <br/>
		 * For example: "an+example%20string" -> "an example string"
		 */
		private String decodePercent( String str ) throws InterruptedException
		{
			try
			{
				StringBuffer sb = new StringBuffer();
				for( int i=0; i<str.length(); i++ )
				{
					char c = str.charAt( i );
					switch ( c )
					{
						case '+':
							sb.append( ' ' );
							break;
						case '%':
							sb.append((char)Integer.parseInt( str.substring(i+1,i+3), 16 ));
							i += 2;
							break;
						default:
							sb.append( c );
							break;
					}
				}
				return sb.toString();
			}
			catch( Exception e )
			{
				sendError( HTTP_BADREQUEST, "BAD REQUEST: Bad percent-encoding." );
				return null;
			}
		}

		/**
		 * Decodes parameters in percent-encoded URI-format
		 * ( e.g. "name=Jack%20Daniels&pass=Single%20Malt" ) and
		 * adds them to given Properties. NOTE: this doesn't support multiple
		 * identical keys due to the simplicity of Properties -- if you need multiples,
		 * you might want to replace the Properties with a Hashtable of Vectors or such.
		 */
		private void decodeParms( String parms, Properties p )
			throws InterruptedException
		{
			if (TextUtils.isEmpty(parms))
				return;

			StringTokenizer st = new StringTokenizer( parms, "&" );
			while ( st.hasMoreTokens())
			{
				String e = st.nextToken();
				int sep = e.indexOf( '=' );
				if ( sep >= 0 )
					Logger.d(Logger._JN, "decodeParms params %s value :%s ", e.substring( 0, sep ).trim(),e.substring( sep+1 ));
					p.put( decodePercent( e.substring( 0, sep )).trim(),
						   decodePercent( e.substring( sep+1 )));
			}
		}

		/**
		 * Returns an error message as a HTTP response and
		 * throws InterruptedException to stop further request processing.
		 */
		private void sendError( String status, String msg ) throws InterruptedException
		{
			sendResponse( status, MIME_PLAINTEXT, null, new ByteArrayInputStream( msg.getBytes()));
			throw new InterruptedException();
		}

		/**
		 * Sends given response to the socket.
		 */
		private void sendResponse( String status, String mime, Properties header, InputStream data )
		{
			try
			{
				if ( status == null )
					throw new Error( "sendResponse(): Status can't be null." );

				OutputStream out = mySocket.getOutputStream();
				PrintWriter pw = new PrintWriter( out );
				pw.print("HTTP/1.0 " + status + " \r\n");

				if ( mime != null )
					pw.print("Content-Type: " + mime + "\r\n");

				if ( header == null || header.getProperty( "Date" ) == null )
					pw.print( "Date: " + gmtFrmt.format( new Date()) + "\r\n");

				if ( header != null )
				{
					Enumeration e = header.keys();
					while ( e.hasMoreElements())
					{
						String key = (String)e.nextElement();
						String value = header.getProperty( key );
						pw.print( key + ": " + value + "\r\n");
					}
				}

				pw.print("\r\n");
				pw.flush();

				if ( data != null )
				{
					int pending = data.available();	// This is to support partial sends, see serveFile()
					byte[] buff = new byte[2048];
					while (pending>0)
					{
						int read = data.read( buff, 0, ( (pending>2048) ?  2048 : pending ));
						if (read <= 0)	break;
						out.write( buff, 0, read );
						pending -= read;
					}
				}
				out.flush();
				out.close();
				if ( data != null )
					data.close();
			}
			catch( IOException ioe )
			{
				ioe.printStackTrace();
				// Couldn't write? No can do.
				try { mySocket.close(); } catch( Throwable t ) {}
			}
		}

		private Socket mySocket;
	}

	/**
	 * URL-encodes everything between "/"-characters.
	 * Encodes spaces as '%20' instead of '+'.
	 */
	private String encodeUri( String uri )
	{
		String newUri = "";
		StringTokenizer st = new StringTokenizer( uri, "/ ", true );
		while ( st.hasMoreTokens())
		{
			String tok = st.nextToken();
			if ( tok.equals( "/" ))
				newUri += "/";
			else if ( tok.equals( " " ))
				newUri += "%20";
			else
			{
				newUri += URLEncoder.encode( tok );
				// For Java 1.4 you'll want to use this instead:
				// try { newUri += URLEncoder.encode( tok, "UTF-8" ); } catch ( java.io.UnsupportedEncodingException uee ) {}
			}
		}
		return newUri;
	}


	private final ServerSocket myServerSocket;
	private Thread myThread;

	// ==================================================
	// File server code
	// ==================================================

	/**
	 * Serves file from homeDir and its' subdirectories (only).
	 * Uses only URI, ignores all headers and HTTP parameters.
	 */
	public Response serveFile(String uri, Properties header)
	{
		Response res = null;
		Logger.d(Logger._JN, "newURI  :%s ", uri);
		if (uri == null) {
			res = new Response(HTTP_NOTFOUND, MIME_PLAINTEXT,
					"Error 404, file not found.");
		}

		try
		{
			String playUrl = UcastUrlLoader.getInstance().getUrl(uri);
			if (!TextUtils.isEmpty(playUrl)){
				Logger.d(Logger._JN, "playUrl  :%s ", playUrl);
				res = new Response(HTTP_OK, MIME_DEFAULT_BINARY, playUrl);
				res.addHeader( "Content-Length", "" + playUrl.getBytes().length);
			}


            File f = new File(uri);
            if (res == null &&  (!f.exists() || !f.isFile())) {
                res = new Response(HTTP_NOTFOUND, MIME_PLAINTEXT,
                        "Error 404, file not found.");
            }

			if ( res == null )
			{
				// Get MIME type from file name extension, if possible
				String mime = null;
				int dot = f.getCanonicalPath().lastIndexOf( '.' );
				if ( dot >= 0 )
					mime = (String)theMimeTypes.get( f.getCanonicalPath().substring( dot + 1 ).toLowerCase());
				if ( mime == null )
					mime = MIME_DEFAULT_BINARY;

				// Support (simple) skipping:
				long startFrom = 0;
				long endAt = -1;
				//{host=192.168.0.116:9192, content-length=0, user-agent=Fiddler}
				String range = header.getProperty( "range" );
				if ( range != null && !mime.startsWith("image"))//图片不支持分段
				{
					if ( range.startsWith( "bytes=" ))
					{
						range = range.substring( "bytes=".length());
						int minus = range.indexOf( '-' );
						try {
							if ( minus > 0 )
							{
								startFrom = Long.parseLong( range.substring( 0, minus ));
								endAt = Long.parseLong( range.substring( minus+1 ));
							}
						}
						catch ( NumberFormatException nfe ) {}
					}
				}

				// Change return code and add Content-Range header when skipping is requested
				long fileLen = f.length();
				if (range != null && startFrom >= 0)
				{
					if ( startFrom >= fileLen)
					{
						res = new Response( HTTP_RANGE_NOT_SATISFIABLE, MIME_PLAINTEXT, "" );
						res.addHeader( "Content-Range", "bytes 0-0/" + fileLen);
					}
					else
					{
						if ( endAt < 0 )
							endAt = fileLen-1;
						long newLen = endAt - startFrom + 1;
						if ( newLen < 0 ) newLen = 0;

						final long dataLen = newLen;
						FileInputStream fis = new FileInputStream( f ) {
							public int available() throws IOException { return (int)dataLen; }
						};
						fis.skip( startFrom );

						res = new Response( HTTP_PARTIALCONTENT, mime, fis );
						res.addHeader( "Content-Length", "" + dataLen);
						res.addHeader( "Content-Range", "bytes " + startFrom + "-" + endAt + "/" + fileLen);
					}
				}
				else
				{
                    if (mime.startsWith("image")) {//进行图片压缩
						byte[] imgBuff = getimage(f.getPath());
						fileLen = imgBuff.length;
                        res = new Response( HTTP_OK, mime, new ByteArrayInputStream(imgBuff));
                    } else {
                        res = new Response( HTTP_OK, mime, new FileInputStream( f ));
                    }
					res.addHeader( "Content-Length", "" + fileLen);
				}
			}
		}
		catch(Exception ioe )
		{
			res = new Response( HTTP_FORBIDDEN, MIME_PLAINTEXT, "FORBIDDEN: Reading file failed." );
		}

		res.addHeader( "Accept-Ranges", "bytes"); // Announce that the file server accepts partial content requestes
		return res;
	}

	/**
	 * Hashtable mapping (String)FILENAME_EXTENSION -> (String)MIME_TYPE
	 */
	private static Hashtable theMimeTypes = new Hashtable();
	static
	{
		StringTokenizer st = new StringTokenizer(
			"css		text/css "+
			"js			text/javascript "+
			"htm		text/html "+
			"html		text/html "+
			"txt		text/plain "+
			"asc		text/plain "+
			"gif		image/gif "+
			"jpg		image/jpeg "+
			"jpeg		image/jpeg "+
			"png		image/png "+
			"mp3		audio/mpeg "+
			"m3u		audio/mpeg-url " +
			"mp4		video/mp4;charset=UTF-8 " +
			"pdf		application/pdf "+
			"doc		application/msword "+
			"ogg		application/x-ogg "+
			"zip		application/octet-stream "+
			"exe		application/octet-stream "+
			"class		application/octet-stream " );
		while ( st.hasMoreTokens())
			theMimeTypes.put( st.nextToken(), st.nextToken());
	}

	/**
	 * GMT date formatter
	 */
	private static java.text.SimpleDateFormat gmtFrmt;
	static
	{
		gmtFrmt = new java.text.SimpleDateFormat( "E, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
		gmtFrmt.setTimeZone(TimeZone.getTimeZone("GMT"));
	}

	private static final String TAG = "HttpServer";
	private static SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss.SSS");
	public static void sPrintln(String msg) {
		//2019-11-15 17:35:14.458 /637/ DevicesConnHandler: gettimer:interval=2000
		String time = sFormat.format(new Date());
		String textLog = String.format("%s /%d/ %s: %s", time, Thread.currentThread().getId(), TAG, msg);
		System.out.println(textLog);
		Logger.d(Logger._JN, "sPrintln  :%s ",msg );
	}


    private static byte[] compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
        int options = 90;
        while (baos.toByteArray().length / 1024 > 1024) { // 循环判断如果压缩后图片是否大于1024kb,大于继续压缩
			sPrintln("压缩 compressImage  options=" + options);
            baos.reset(); // 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%,把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
        }
        return baos.toByteArray();
    }

    private static byte[] getimage(String srcPath) {

        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // 开始读入图片,此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);// 此时返回bm为空
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;

        float hh = 1800;// 这里设置高度
        float ww = 2400;// 这里设置宽度
        // 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
        int be = 1;// be=1表示不缩放
        if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;// 设置缩放比例
		sPrintln("缩放比例 inSampleSize=" + be);
        // 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        return compressImage(bitmap);// 压缩好比例大小后再进行质量压缩
    }

}


用服务的形式启动服务端,防止掉线。
HttpService:

package example.com.httpserver;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.annotation.Nullable;

;

/**
 * ================================================
 * 作    者:xujianjing
 * 版    本:v1.0
 * 创建日期:2019/11/1
 * 描    述:
 * 修订历史:
 * ================================================
 */
public class HttpService extends Service {

    private  HttpServer mHttpServer;
    private static int sTcpPort = -1;
    private Handler mHandler = new Handler(Looper.getMainLooper());

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public void onCreate() {
        super.onCreate();
        Logger.d(Logger._TJ, "HttpService onCreate");
        startHttp();
    }

    private void startHttp() {
        mHttpServer =  HttpServer.safeStart();
        if (mHttpServer != null) {
            sTcpPort = mHttpServer.getTcpPort();
            mHttpServer.setOnExitHandler(mOnExitHandler);
            Logger.d(Logger._TJ, "startHttp success, post:" + sTcpPort);
            String requestUrl = "http://" + NetworkUtil.getIp() + ":" + HttpService.getHttpServerPort() +"/";
            Logger.d(Logger._JN, "startHttp :%s ", requestUrl);
        } else {
            Logger.e("startHttp failed");
            stopSelf();
        }
    }

     HttpServer.IOnExitHandler mOnExitHandler = new HttpServer.IOnExitHandler() {
        @Override
        public void onExitHandler(Throwable t) {
            mHttpServer = null;
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    System.gc();
                    startHttp();
                }
            }, 1000);
        }
    };

    @Override
    public void onDestroy() {
        mHandler.removeCallbacksAndMessages(null);
        if (mHttpServer != null) {
            mHttpServer.stop();
        }
        sTcpPort = -1;
        super.onDestroy();
    }

    public static int getHttpServerPort() {
        return sTcpPort;
    }
}

这样,简单的服务端就做好了,可以用工具Fiddler工具进行测试。
在这里插入图片描述
其中,/path/下的数据,可以自己做一个简单的存储工具,返回响应的信息。
代码如下:

package example.com.httpserver;

import android.text.TextUtils;
import android.util.LruCache;

/**
 * ================================================
 * 作    者:zhoujianan
 * 版    本:v1.0
 * 创建日期:2020/4/15
 * 描    述:
 * 修订历史:
 * ================================================
 */
public class UcastUrlLoader {
    private LruCache<String, String> mUrlList;
    private static UcastUrlLoader mUcastUrlLoader;
    private UcastUrlLoader() {
        int maxMemory = (int) Runtime.getRuntime().maxMemory();
        Logger.d(Logger._JN, "UcastUrlLoader maxMemory :%s ", maxMemory);
        int cacheSize = 10 * 1024 * 1024;
        Logger.d(Logger._JN, "UcastUrlLoader cacheSize :%s ", cacheSize);
        mUrlList = new LruCache<String, String>(cacheSize){
            @Override
            protected int sizeOf(String key, String value) {
                return value.getBytes().length;
            }
        };
    }

    public static UcastUrlLoader getInstance() {
        if (mUcastUrlLoader == null) {
            mUcastUrlLoader = new UcastUrlLoader();
            mUcastUrlLoader.addUrl("xxx","sdfsdfsdf");
            mUcastUrlLoader.addUrl("111","111");
            mUcastUrlLoader.addUrl("222","222");
            mUcastUrlLoader.addUrl("333","333");
            mUcastUrlLoader.addUrl("test","返回结果 哈哈哈哈");
            Logger.d(Logger._JN, " new UcastUrlLoader()" );
        }
        return mUcastUrlLoader;
    }

    public void addUrl(String key, String value) {
        if (!TextUtils.isEmpty(key) && !TextUtils.isEmpty(value)) {
            mUrlList.put(key, value);
        }
    }

    public String getUrl(String key) {
        return mUrlList.get(key);
    }

    public String remove(String key) {
        return mUrlList.remove(key);
    }


}

NetworkUtil.java

package example.com.httpserver;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.support.annotation.RequiresPermission;
import android.telephony.TelephonyManager;

import example.LocalApplication;


/**
 * ================================================
 * 作    者:xujianjing
 * 版    本:v1.0
 * 创建日期:2019/9/11
 * 描    述:
 * 修订历史:
 * ================================================
 */
public class NetworkUtil {
    private NetworkUtil() {
        throw new UnsupportedOperationException("u can't instantiate me...");
    }

    @RequiresPermission("android.permission.ACCESS_NETWORK_STATE")
    private static NetworkInfo getActiveNetworkInfo(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo();
    }

    /**
     * 获取当前网络类型
     * 需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>}
     */
    @RequiresPermission("android.permission.ACCESS_NETWORK_STATE")
    public static NetworkType getNetworkType(Context context) {
        NetworkType netType = NetworkType.NETWORK_NO;
        NetworkInfo info = getActiveNetworkInfo(context);
        if (info != null && info.isAvailable()) {

            if (info.getType() == ConnectivityManager.TYPE_WIFI) {
                netType = NetworkType.NETWORK_WIFI;
            } else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
                switch (info.getSubtype()) {

                    case TelephonyManager.NETWORK_TYPE_TD_SCDMA:
                    case TelephonyManager.NETWORK_TYPE_EVDO_A:
                    case TelephonyManager.NETWORK_TYPE_UMTS:
                    case TelephonyManager.NETWORK_TYPE_EVDO_0:
                    case TelephonyManager.NETWORK_TYPE_HSDPA:
                    case TelephonyManager.NETWORK_TYPE_HSUPA:
                    case TelephonyManager.NETWORK_TYPE_HSPA:
                    case TelephonyManager.NETWORK_TYPE_EVDO_B:
                    case TelephonyManager.NETWORK_TYPE_EHRPD:
                    case TelephonyManager.NETWORK_TYPE_HSPAP:
                        netType = NetworkType.NETWORK_3G;
                        break;

                    case TelephonyManager.NETWORK_TYPE_LTE:
                    case TelephonyManager.NETWORK_TYPE_IWLAN:
                        netType = NetworkType.NETWORK_4G;
                        break;

                    case TelephonyManager.NETWORK_TYPE_GSM:
                    case TelephonyManager.NETWORK_TYPE_GPRS:
                    case TelephonyManager.NETWORK_TYPE_CDMA:
                    case TelephonyManager.NETWORK_TYPE_EDGE:
                    case TelephonyManager.NETWORK_TYPE_1xRTT:
                    case TelephonyManager.NETWORK_TYPE_IDEN:
                        netType = NetworkType.NETWORK_2G;
                        break;
                    default:
                        String subtypeName = info.getSubtypeName();
                        if (subtypeName.equalsIgnoreCase("TD-SCDMA")
                                || subtypeName.equalsIgnoreCase("WCDMA")
                                || subtypeName.equalsIgnoreCase("CDMA2000")) {
                            netType = NetworkType.NETWORK_3G;
                        } else {
                            netType = NetworkType.NETWORK_UNKNOWN;
                        }
                        break;
                }
            } else {
                netType = NetworkType.NETWORK_UNKNOWN;
            }
        }
        return netType;
    }

    public enum NetworkType {

        NETWORK_WIFI("WiFi"),
        NETWORK_4G("4G"),
        NETWORK_2G("2G"),
        NETWORK_3G("3G"),
        NETWORK_UNKNOWN("Unknown"),
        NETWORK_NO("No network");

        private String desc;
        NetworkType(String desc) {
            this.desc = desc;
        }

        @Override
        public String toString() {
            return desc;
        }
    }

    public static String getIp( ) {
        @SuppressLint("WifiManagerLeak") WifiManager wifiMg = (WifiManager) LocalApplication.getContext().getSystemService(Context.WIFI_SERVICE);
        if (!wifiMg.isWifiEnabled()) {
            return "";
        }
        WifiInfo wifiInfo = wifiMg.getConnectionInfo();
        Logger.d(Logger._TJ, "wifi isWifiEnabled = %s,  WifiName=%s    WifiInfo=>%s", wifiMg.isWifiEnabled(), wifiInfo.getSSID(), wifiInfo);
        if (wifiInfo != null) {
            Logger.d(Logger._JN, "getIp Address :%s ", wifiInfo.getIpAddress());
            int i = wifiInfo.getIpAddress();
            return (i & 0xFF) + "." +
                    ((i >> 8) & 0xFF) + "." +
                    ((i >> 16) & 0xFF) + "." +
                    (i >> 24 & 0xFF);

        }
        return "";
    }
}

启动服务:


import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import example.com.httpserver.HttpService;
import example.com.httpserver.Logger;
import example.com.tvpartner.R;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Logger.d(Logger._JN, "onCreate()");
        startService(new Intent(this, HttpService.class));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopService(new Intent(this, HttpService.class));
    }
}

注意: 客户端和服务端一定要记得在AndroidManifest.xml中注册网络监听,并要保持在同一个局域网下,才可以进行通信。

下面,开始客户端简单请求代码:

package example.com.httpclient.view;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

import example.com.httpclient.Logger;
import example.com.httpclient.R;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.HttpException;

public class MainActivity extends AppCompatActivity {
    private TextView mResponseTv;
    Disposable subscribe;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mResponseTv = findViewById(R.id.tv_response);
        findViewById(R.id.btn_request).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (subscribe != null && !subscribe.isDisposed()) {
                    subscribe.dispose();
                }
                subscribe = Observable.just("")
                        .map(new Function<String, String>() {
                            @Override
                            public String apply(String s) throws Exception {
                                Logger.d(Logger._JN, "onClick()");
                                Request request = new Request.Builder()
                                        .url("http://192.168.0.111:9193/path/111")
                                        .build();
                                Call call = new OkHttpClient().newCall(request);
                                Response response = call.execute();
                                if (response.isSuccessful()) {
                                    Logger.d(Logger._JN, "response : %s ", response);
                                    return response.body().string();
                                }
                                throw new HttpException(retrofit2.Response.error(response.code(), response.body()));
                            }
                        })
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribeOn(Schedulers.io())
                        .subscribe(new Consumer<String>() {
                            @Override
                            public void accept(String response) throws Exception {
                                mResponseTv.setText(response);
                            }
                        }, new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                Logger.e("request url error " + throwable.getMessage());
                            }
                        });
            }
        });

    }
}

main_activity.layout

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".view.MainActivity">


    <Button
        android:id="@+id/btn_request"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="request"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <TextView
        android:id="@+id/tv_response"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"/>
</android.support.constraint.ConstraintLayout>

介绍一下,这个小型手机端服务器在项目中的应用场景:
主要是应用于,发送方需要发送超长的字符串给接收方,但接收方并不能通过双方的传输机制接受这么长的字符串,则,通过此方法,先通过发送方发送简单的请求字符串,让接收方接收该字符串后,通过局域网的TCP请求,拼接局域网ip+端口号+请求字符串请求发送方,发送方将需要传输的超长字符串存储在响应体中,这样,就可以完成传输了。
解释如图:
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值