首页 技术 正文
技术 2022年11月6日
0 收藏 681 点赞 771 浏览 9748 个字

手机服务器微架构设计与实现 之 http server

·应用

手机服务器微架构设计与实现 之 http server

手机服务器微架构设计与实现 之 http server

·传输协议和应用层协议概念

手机服务器微架构设计与实现 之 http server

TCP

手机服务器微架构设计与实现 之 http server

 UDP

手机服务器微架构设计与实现 之 http server

 TCP和UDP选择

手机服务器微架构设计与实现 之 http server

三次握手(客户端与服务器端建立连接)/四次挥手(断开连接)过程图

手机服务器微架构设计与实现 之 http server

·java Socket 基础

手机服务器微架构设计与实现 之 http server

手机服务器微架构设计与实现 之 http server

·Get 与 Post 协议格式

手机服务器微架构设计与实现 之 http server

手机服务器微架构设计与实现 之 http server

·开发真机与模拟器网络调试工具与配置

 真机:开发机和真机处于同一网段下即可

 模拟器:

手机服务器微架构设计与实现 之 http server

·关键代码

 package com.example.lifen.simplehttpserver; import android.util.Log; import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; /**
* Created by LiFen on 2017/12/27.
*/ public class SimpleHttpServer {
private static final String TAG = "SimpleHttpServer";
private final WebConfiguration webConfig;
private final ExecutorService threadPool;//线程池
private final HashSet<IRsourceUriHandler> resourceUriHandlers;
private boolean isEnable;
private ServerSocket socket; public SimpleHttpServer(WebConfiguration webConfig){
this.webConfig = webConfig;
threadPool = Executors.newCachedThreadPool();
resourceUriHandlers = new HashSet<>();
} public void registerResourceHandler(IRsourceUriHandler iRsourceUriHandler){
resourceUriHandlers.add(iRsourceUriHandler);
} /**
* 启动Server(异步)
*/
public void startAsync(){
isEnable = true;
new Thread(new Runnable() {
@Override
public void run() {
doProcSync();
}
}).start();
} /**
* 停止Server(异步)
*/
public void stopAsync() {
if(!isEnable){
return;
}
isEnable = false;
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
socket = null;
} private void doProcSync() {
Log.d(TAG, "doProcSync() called");
try {
InetSocketAddress socketAddr = new InetSocketAddress(webConfig.getPort());
socket = new ServerSocket();
socket.bind(socketAddr);
while(isEnable){
final Socket remotePeer = socket.accept();
threadPool.submit(new Runnable() {
@Override
public void run() {
onAcceptRemotePeer(remotePeer);
}
});
}
} catch (IOException e) {
Log.e(TAG, "doProcSync: e ", e);
}
} /**
* 一个HTTP请求报文由请求行(request line)、请求头部(header)、空行和请求数据4个部分组成
* @param remotePeer
*/
private void onAcceptRemotePeer(Socket remotePeer) {
Log.d(TAG, "onAcceptRemotePeer() called with: remotePeer.getRemoteSocketAddress() = [" + remotePeer.getRemoteSocketAddress() + "]");
HttpContext httpContext = new HttpContext();
try {
// remotePeer.getOutputStream().write("congratulations, connected success".getBytes());
httpContext.setUnderlySocket(remotePeer);
InputStream nis = remotePeer.getInputStream();
String headerLine = null;
String readLine = StreamToolkit.readLine(nis);//http请求行(request line)1
Log.i(TAG, "http 1 请求行 readLine =" + readLine);
//测试请求行结果 readLine =POST /get/?key=dddd&sss=123456 HTTP/1.1
httpContext.setType(readLine.split(" ")[0]);
String resourceUri = headerLine = readLine.split(" ")[1];
Log.i(TAG, "地址 =" + headerLine);
while ((headerLine = StreamToolkit.readLine(nis)) != null) {//http请求头部(header)2 if (headerLine.equals("\r\n")) {//http请求空行3
Log.i(TAG, "http 3 请求头部 /r/n ");
break;
}
Log.i(TAG, "http 2 请求头部 headerLine = " + headerLine);
String[] pair = headerLine.split(": ");
if (pair.length > 1) {
httpContext.addRequestHeader(pair[0], pair[1]);
}
} for (IRsourceUriHandler handler : resourceUriHandlers) {
if (!handler.accept(resourceUri)) {
continue;
}
handler.postHandle(resourceUri, httpContext);//http请求数据4
}
} catch (IOException e) {
Log.e("spy",e.toString());
}finally {//只要流或socket不关闭,浏览器就收不到信息
try {
remotePeer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
 package com.example.lifen.simplehttpserver; import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView; public class MainActivity extends AppCompatActivity { private SimpleHttpServer shs;
private ImageView imageView; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView); WebConfiguration wc = new WebConfiguration();
wc.setPort(8088);
wc.setMaxParallels(50); shs = new SimpleHttpServer(wc);
/*
向 shs 中添加 IRsourceUriHander 实例
*/
shs.registerResourceHandler(new ResourceInAssetsHandler(this));
shs.registerResourceHandler(new UploadImageHandler(this){
@Override
public void onImageLoaded(final String path) {//重写onImageLoaded方法 在UiTread 主线程中更新Ui
runOnUiThread(new Runnable() {
@Override
public void run() {
Bitmap bitmap = BitmapFactory.decodeFile(path);
imageView.setImageBitmap(bitmap);
}
});
}
}); shs.startAsync();
} @Override
protected void onDestroy() {
super.onDestroy();
shs.stopAsync();
}
}
 package com.example.lifen.simplehttpserver; import android.content.Context;
import android.util.Log; import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream; /**
* Created by LiFen on 2017/12/29.
*/ public class ResourceInAssetsHandler implements IRsourceUriHandler {
private static final String TAG = "ResourceInAssetsHandler";
private String acceptPrefix = "/static/";
private Context context; public ResourceInAssetsHandler(Context context){
this.context = context;
} @Override
public boolean accept(String uri) {
/*
判断uri 是否以 “/static/" 开始
*/
return uri.startsWith(acceptPrefix);
} @Override
public void postHandle(String uri, HttpContext httpContext) throws IOException{
Log.d(TAG, "postHandle() called with: uri = [" + uri + "], httpContext = [" + httpContext + "]");
/*
截取assets 文件夹下静态网页相对路径
*/
int startIndex = acceptPrefix.length();
String assetsPath = uri.substring(startIndex);
Log.i(TAG, "assetsPath: " + assetsPath); /*
打开静态网页 返回一个输入流 转化为 byte[]
*/
InputStream inputStream = context.getAssets().open(assetsPath);//打开文件 返回一个输入流
byte[] raw = StreamToolkit.readRawFromStream(inputStream);
Log.i(TAG, "assetsPath "+ "raw =" + raw.length);
inputStream.close(); OutputStream outputStream = httpContext.getUnderlySocket().getOutputStream();//获取当前Socket的输出流
PrintStream printWriter = new PrintStream(outputStream);//输出符合http协议的信息给浏览器
printWriter.println("HTTP/1.1 200 OK");
printWriter.println("Content-Length:" + raw.length); if(assetsPath.endsWith(".html")){
printWriter.println("Content-Type:text/html");
}else if(assetsPath.endsWith(".js")){
printWriter.println("Content-Type:text/js");
}else if(assetsPath.endsWith(".css")){
printWriter.println("Content-Type:text/css");
}else if(assetsPath.endsWith(".jpg")){
printWriter.println("Content-Type:text/jpg");
}else if(assetsPath.endsWith(".png")){
printWriter.println("Content-Type:text/png");
}
printWriter.println(); printWriter.write(raw);
Log.i(TAG, "postHandle: over");
}
}
 package com.example.lifen.simplehttpserver; import android.app.Activity;
import android.os.Environment;
import android.util.Log; import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter; /**
* Created by LiFen on 2017/12/30.
*/ class UploadImageHandler implements IRsourceUriHandler {
private static final String TAG = "UploadImageHandler";
String acceptPrefix = "/image/";
Activity activity; public UploadImageHandler(Activity activity){
this.activity = activity;
} @Override
public boolean accept(String uri) {
return uri.startsWith(acceptPrefix);
} @Override
public void postHandle(String uri, HttpContext httpContext) throws IOException {
long totalLength = Long.parseLong(httpContext.getRequestHeaderValue("Content-Length").trim());
/*
将 接收到的 图片存储到本机 SD卡目录下
*/
File file = new File(Environment.getExternalStorageDirectory(),
"tmpFile.jpg");
Log.i(TAG, "postHandle: " +"totalLength=" + totalLength + " file getPath=" + file.getPath() );
if(file.exists()){
file.delete();
}
byte[] buffer = new byte[10240];
int read;
long nLeftLength = totalLength;
FileOutputStream fileOutputStream = new FileOutputStream(file.getPath());//文件输出流
InputStream inputStream = httpContext.getUnderlySocket().getInputStream();//从当前 Socket 中得到文件输入流
while (nLeftLength > 0 && (read = inputStream.read(buffer)) > 0){//写到文件输出流中,即存储到SD 卡路径下
fileOutputStream.write(buffer,0,read);
nLeftLength -= read;
}
Log.i(TAG, "postHandle: close");
fileOutputStream.close(); /*
从当前 Socket 中得到 文件输出流,将 符合http协议的信息 返回给浏览器
*/
OutputStream outputStream = httpContext.getUnderlySocket().getOutputStream();
PrintWriter printWriter = new PrintWriter(outputStream);
printWriter.print("HTTP/1.1 200 OK");
printWriter.println();
/*
记录图片存储的位置
*/
onImageLoaded(file.getPath());
} public void onImageLoaded(String path){
Log.d(TAG, "onImageLoaded() called with: path = [" + path + "]");
}
}
 package com.example.lifen.simplehttpserver; import java.net.Socket;
import java.util.HashMap;
import java.util.Map; /**
* Created by LiFen on 2017/12/28.
*/ public class HttpContext {
private Socket underlySocket;
Map<String,String> heard = new HashMap<>();
private String type; public void setUnderlySocket(Socket underlySocket){
this.underlySocket = underlySocket;
} public void addRequestHeader(String key,String value){
heard.put(key,value);
} public Socket getUnderlySocket(){
return underlySocket;
} public String getRequestHeaderValue(String key){
return heard.get(key);
} public String getType(){
return type;
} public void setType(String type){
this.type = type;
}
}
 package com.example.lifen.simplehttpserver; import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream; /**
* Created by LiFen on 2017/12/27.
*/ public class StreamToolkit {
public static final String readLine(InputStream nis) throws IOException {
StringBuffer sb = new StringBuffer();
int c1 = 0;
int c2 = 0;
while (c2 != -1 && !(c1 == '\r' && c2 == '\n')){
c1 = c2;
c2 = nis.read();
sb.append((char)c2);
}
if(sb.length() == 0) {
return null;
}
return sb.toString();
} public static byte[] readRawFromStream(InputStream inputStream) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[10240];
int read;
while ((read = inputStream.read(buffer)) > 0){
outputStream.write(buffer,0,read);
}
return outputStream.toByteArray();
} }
 package com.example.lifen.simplehttpserver; /**
* Created by LiFen on 2017/12/27.
*/ public class WebConfiguration {
/**
* 端口
*/
private int port;
/**
* 最大监听数
*/
private int maxParallels; public int getPort() {
return port;
} public void setPort(int port) {
this.port = port;
} public int getMaxParallels() {
return maxParallels;
} public void setMaxParallels(int maxParallels) {
this.maxParallels = maxParallels;
}
}
 package com.example.lifen.simplehttpserver; import java.io.IOException; /**
* Created by LiFen on 2017/12/29.
*/ public interface IRsourceUriHandler {
boolean accept(String uri);
void postHandle(String uri, HttpContext httpContext) throws IOException;
}

此项目github下载地址:

https://github.com/li-fengjie/SimpleHttpServer

win10正式版telnet不是内部或外部命令解决办法:

https://jingyan.baidu.com/article/1e5468f9033a71484961b7d7.html

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,965
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,486
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,331
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,114
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,747
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,781