use of com.firenio.codec.http11.HttpFrame in project baseio by generallycloud.
the class TestHttpLoadServerTFB method main.
public static void main(String[] args) throws Exception {
System.setProperty("core", "1");
System.setProperty("frame", "16");
System.setProperty("readBuf", "512");
System.setProperty("pool", "true");
System.setProperty("inline", "true");
System.setProperty("level", "1");
System.setProperty("read", "false");
System.setProperty("epoll", "true");
System.setProperty("nodelay", "true");
System.setProperty("cachedurl", "true");
System.setProperty("unsafeBuf", "false");
boolean lite = Util.getBooleanProperty("lite");
boolean read = Util.getBooleanProperty("read");
boolean pool = Util.getBooleanProperty("pool");
boolean epoll = Util.getBooleanProperty("epoll");
boolean direct = Util.getBooleanProperty("direct");
boolean nodelay = Util.getBooleanProperty("nodelay");
boolean cachedurl = Util.getBooleanProperty("cachedurl");
boolean unsafeBuf = Util.getBooleanProperty("unsafeBuf");
int core = Util.getIntProperty("core", 1);
int frame = Util.getIntProperty("frame", 16);
int level = Util.getIntProperty("level", 1);
int readBuf = Util.getIntProperty("readBuf", 16);
LoggerFactory.setEnableSLF4JLogger(false);
LoggerFactory.setLogLevel(LoggerFactory.LEVEL_INFO);
Options.setBufAutoExpansion(false);
Options.setChannelReadFirst(read);
Options.setEnableEpoll(epoll);
Options.setEnableUnsafeBuf(unsafeBuf);
DebugUtil.info("lite: {}", lite);
DebugUtil.info("read: {}", read);
DebugUtil.info("pool: {}", pool);
DebugUtil.info("core: {}", core);
DebugUtil.info("epoll: {}", epoll);
DebugUtil.info("frame: {}", frame);
DebugUtil.info("level: {}", level);
DebugUtil.info("readBuf: {}", readBuf);
DebugUtil.info("nodelay: {}", nodelay);
DebugUtil.info("cachedurl: {}", cachedurl);
DebugUtil.info("unsafeBuf: {}", unsafeBuf);
int processors = Util.availableProcessors() * core;
int fcache = 1024 * 16;
int pool_unit = 256 * 16;
int pool_cap = 1024 * 8 * pool_unit * processors;
String server = "firenio";
ByteTree cachedUrls = null;
if (cachedurl) {
cachedUrls = new ByteTree();
cachedUrls.add("/plaintext");
cachedUrls.add("/json");
}
HttpCodec codec = new HttpCodec(server, fcache, lite, cachedUrls) {
@Override
protected Object newAttachment() {
return new MyHttpAttachment();
}
};
IoEventHandle eventHandle = new IoEventHandle() {
@Override
public void accept(Channel ch, Frame frame) throws Exception {
HttpFrame f = (HttpFrame) frame;
String action = f.getRequestURL();
if ("/plaintext".equals(action)) {
MyHttpAttachment att = (MyHttpAttachment) ch.getAttachment();
ByteBuf buf = att.write_buf;
if (buf == null) {
buf = ch.allocate();
ByteBuf temp = buf;
att.write_buf = buf;
ch.getEventLoop().submit(() -> {
ch.writeAndFlush(temp);
att.write_buf = null;
});
}
f.setContent(STATIC_PLAINTEXT);
f.setContentType(HttpContentType.text_plain);
f.setConnection(HttpConnection.NONE);
f.setDate(HttpDateUtil.getDateLine());
codec.encode(ch, buf, f);
codec.release(ch.getEventLoop(), f);
} else if ("/json".equals(action)) {
ByteBuf temp = FastThreadLocal.get().getAttribute(JSON_BUF);
if (temp == null) {
temp = ByteBuf.heap(0);
FastThreadLocal.get().setAttribute(JSON_BUF, temp);
}
JsonStream stream = JsonStreamPool.borrowJsonStream();
try {
stream.reset(null);
stream.writeVal(Message.class, new Message("Hello, World!"));
Slice slice = stream.buffer();
temp.reset(slice.data(), slice.head(), slice.tail());
f.setContent(temp);
f.setContentType(HttpContentType.application_json);
f.setConnection(HttpConnection.NONE);
f.setDate(HttpDateUtil.getDateLine());
ch.writeAndFlush(f);
ch.release(f);
} finally {
JsonStreamPool.returnJsonStream(stream);
}
} else {
System.err.println("404");
f.setString("404,page not found!", ch);
f.setContentType(HttpContentType.text_plain);
f.setStatus(HttpStatus.C404);
f.setDate(HttpDateUtil.getDateLine());
ch.writeAndFlush(f);
ch.release(f);
}
}
};
HttpDateUtil.start();
NioEventLoopGroup group = new NioEventLoopGroup();
ChannelAcceptor context = new ChannelAcceptor(group, 8081);
group.setMemoryCapacity(pool_cap);
group.setEnableMemoryPool(pool);
group.setMemoryUnit(pool_unit);
group.setWriteBuffers(8);
group.setChannelReadBuffer(1024 * readBuf);
group.setEventLoopSize(Util.availableProcessors() * core);
group.setConcurrentFrameStack(false);
if (nodelay) {
context.addChannelEventListener(new ChannelEventListenerAdapter() {
@Override
public void channelOpened(Channel ch) throws Exception {
ch.setOption(SocketOptions.TCP_NODELAY, 1);
ch.setOption(SocketOptions.SO_KEEPALIVE, 0);
}
});
}
context.addProtocolCodec(codec);
context.setIoEventHandle(eventHandle);
context.bind(1024 * 8);
}
use of com.firenio.codec.http11.HttpFrame in project baseio by generallycloud.
the class TestWebSocketRumpetrollServlet method accept.
@Override
public void accept(Channel ch, Frame frame) throws Exception {
if (frame instanceof HttpFrame) {
HttpFrame f = (HttpFrame) frame;
f.updateWebSocketProtocol(ch);
msgAdapter.addClient(ch.getDesc(), ch);
JSONObject o = new JSONObject();
o.put("type", "welcome");
o.put("id", ch.getChannelId());
WebSocketFrame wsf = new WebSocketFrame();
wsf.setString(o.toJSONString(), ch);
ch.writeAndFlush(wsf);
return;
}
WebSocketFrame f = (WebSocketFrame) frame;
// CLOSE
if (f.isCloseFrame()) {
if (msgAdapter.removeClient(ch) != null) {
JSONObject o = new JSONObject();
o.put("type", "closed");
o.put("id", ch.getChannelId());
msgAdapter.sendMsg(o.toJSONString());
logger.info("客户端主动关闭连接:{}", ch);
}
ch.close();
} else {
String msg = f.getStringContent();
JSONObject o = JSON.parseObject(msg);
String name = o.getString("name");
if (Util.isNullOrBlank(name)) {
name = Util.randomUUID();
}
o.put("name", name);
o.put("id", ch.getChannelId());
String type = o.getString("type");
if ("update".equals(type)) {
o.put("life", "1");
o.put("authorized", "false");
o.put("x", Double.valueOf(o.getString("x")));
o.put("y", Double.valueOf(o.getString("x")));
o.put("momentum", Double.valueOf(o.getString("momentum")));
o.put("angle", Double.valueOf(o.getString("angle")));
} else if ("message".equals(type)) {
}
msgAdapter.sendMsg(o.toJSONString());
}
}
use of com.firenio.codec.http11.HttpFrame in project baseio by generallycloud.
the class HttpFrameHandle method printHtml.
protected void printHtml(Channel ch, Frame frame, HttpStatus status, String content) throws Exception {
HttpFrame f = (HttpFrame) frame;
StringBuilder builder = new StringBuilder(HttpUtil.HTML_HEADER);
builder.append(" <div style=\"margin-left:20px;\">\n");
builder.append(" ");
builder.append(content);
builder.append(" </div>\n");
builder.append(" </div>\n");
builder.append(HttpUtil.HTML_POWER_BY);
builder.append(HttpUtil.HTML_BOTTOM);
byte[] data = builder.toString().getBytes(ch.getCharset());
f.setContent(data);
f.setStatus(status);
f.setContentType(HttpContentType.text_html_utf8);
ch.writeAndFlush(f);
}
use of com.firenio.codec.http11.HttpFrame in project baseio by generallycloud.
the class HttpFrameHandle method acceptHtml.
protected void acceptHtml(Channel ch, Frame frame) throws Exception {
String frameName = HttpUtil.getFrameName(ch, frame);
HttpEntity entity = null;
if (frameName.equals("/")) {
entity = htmlCache.get(welcome);
}
if (entity == null) {
entity = htmlCache.get(frameName);
}
HttpStatus status = HttpStatus.C200;
HttpFrame f = (HttpFrame) frame;
if (entity == null) {
entity = htmlCache.get("/404.html");
if (entity == null) {
printHtml(ch, frame, HttpStatus.C404, "404 page not found");
return;
}
}
File file = entity.getFile();
if (file != null && file.lastModified() > entity.getLastModify()) {
synchronized (entity) {
if (file.lastModified() > entity.getLastModify()) {
reloadEntity(entity, ch.getContext(), status);
}
}
writeAndFlush(ch, f, entity);
return;
}
String ims = f.getRequestHeader(HttpHeader.If_Modified_Since);
long imsTime = -1;
if (!Util.isNullOrBlank(ims)) {
imsTime = DateUtil.get().parseHttp(ims).getTime();
}
if (imsTime < entity.getLastModifyGTMTime()) {
writeAndFlush(ch, f, entity);
return;
}
f.setStatus(HttpStatus.C304);
ch.writeAndFlush(f);
}
use of com.firenio.codec.http11.HttpFrame in project baseio by generallycloud.
the class HttpProxyServer method strtup.
public synchronized void strtup(NioEventLoopGroup group, int port) throws Exception {
if (context != null && context.isActive()) {
return;
}
IoEventHandle eventHandle = new IoEventHandle() {
@Override
public void accept(Channel ch_src, Frame frame) throws Exception {
final HttpFrame f = (HttpFrame) frame;
if (f.getMethod() == HttpMethod.CONNECT) {
ch_src.writeAndFlush(CONNECT_RES_BUF.duplicate());
HttpProxyAttr s = HttpProxyAttr.get(ch_src);
String[] arr = f.getHost().split(":");
s.host = arr[0];
s.port = Integer.parseInt(arr[1]);
s.handshakeFinished = true;
} else {
String host = f.getHost();
String[] arr = host.split(":");
int port = 80;
if (arr.length == 2) {
port = Integer.parseInt(arr[1]);
}
if (f.getRequestHeaders().remove(HttpHeader.Proxy_Connection.getId()) == null) {
return;
}
NioEventLoop el = ch_src.getEventLoop();
ChannelConnector context = new ChannelConnector(el, arr[0], port);
context.addProtocolCodec(new ClientHttpCodec());
context.setIoEventHandle(new IoEventHandle() {
@Override
public void accept(Channel ch, Frame frame) throws Exception {
ClientHttpFrame res = (ClientHttpFrame) frame;
IntObjectMap<String> hs = res.getResponse_headers();
for (hs.scan(); hs.hasNext(); ) {
String v = hs.getValue();
if (v == null) {
continue;
}
if (hs.getKey() == HttpHeader.Content_Length.getId() || hs.getKey() == HttpHeader.Connection.getId() || hs.getKey() == HttpHeader.Transfer_Encoding.getId() || hs.getKey() == HttpHeader.Content_Encoding.getId()) {
continue;
}
f.setResponseHeader(hs.getKey(), v.getBytes());
}
if (res.getContent() != null) {
f.setContent(res.getContent());
} else if (res.isChunked()) {
f.setString("not support chunked now.", ch);
}
ch_src.writeAndFlush(f);
ch.close();
}
});
String url = parseRequestURL(f.getRequestURL());
context.setPrintConfig(false);
context.addChannelEventListener(new LoggerChannelOpenListener());
context.connect((ch, ex) -> {
if (ex == null) {
ClientHttpFrame req = new ClientHttpFrame(url, f.getMethod());
req.setRequestHeaders(f.getRequestHeaders());
req.getRequestHeaders().remove(HttpHeader.Proxy_Connection.getId());
if (f.getMethod() == HttpMethod.POST) {
req.setContent(f.getContent());
}
try {
ch.writeAndFlush(req);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
};
context = new ChannelAcceptor(group, 8088);
context.addProtocolCodec(new HttpProxyCodec());
context.setIoEventHandle(eventHandle);
context.addChannelEventListener(new LoggerChannelOpenListener());
context.bind();
}
Aggregations