const http = require("http");
const net = require("net");
const host = '127.0.0.1';
const port = 8082;
let count = 0;
http.createServer(function (req, res) {
debugger;
count++;
req.on('data', function(){
debugger;
});
req.on('end', async function () {
debugger;
console.log('count(%d)', count);
let data;
data = await getJavaData(count);
res.writeHead(200, { 'Content-Type': 'text/html' });
let content = `<p>${data}</p>`;
res.end(content);
});
}).listen(3000);
//======================================
function getJavaData(count) {
return new Promise(function (res, rej) {
let data = '';
let time = 0;
const client = net.connect(port, host, function () {
console.log('java connect...');
});
client.on('data', function (_data) {
if (time++ == 0) {
data = _data.toString();
console.log('java count(%s) data(%s) data.length', count, data, data.length);
}
});
client.on('end', function () {
console.log('java end...');
res(data);
});
});
}
//////////////////////////////////////////////////////////////////////////////////////
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package test_5;
import java.io.IOException;
import java.io.PrintStream;
import java.net.*;
import static java.lang.System.out;
/**
*
* @author xman
*/
public class Socket_1 {
ServerSocket ss;
Socket socket;
static int port = 8082;
public Socket_1() throws Exception {
ss = new ServerSocket(port);
while(true){
socket = ss.accept();
out.println("connect");
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println("i am java");
ps.close();
socket.close();
out.println("disconnect");
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try{
new Socket_1();
}catch(Exception e){
out.println(e.toString());
}
}
}
2018年12月29日 星期六
2018年12月22日 星期六
java promise
https://my.oschina.net/andylucc/blog/608499
http://ifeve.com/promise-future-callback/
https://github.com/hprose/hprose-java/wiki/%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B%E2%80%94%E2%80%94Promise
https://juejin.im/post/5b126065e51d4506bd72b7cc
https://www.infoq.cn/article/design-patterns-promise https://www.cnkirito.moe/future-and-promise/
interface Closure<E, T> {
public T callback(E in);
public void error(Error err);
}
public class Promise<E> {
protected int status = 0;
protected ArrayList<Closure> jobList = new ArrayList<>();
protected Closure<Promise, Void> job;
protected E data;
public Promise(Closure job){
this.job = job;
// 暴露 resolve, reject
this.job.callback(this);
}
private Promise() {
}
public void resolve(E e){
}
public void reject(String err){
}
protected void reject(Error err){
}
public Promise done(Closure c){
return (new Promise<E>());
}
public Promise error(Closure c){
return (new Promise<E>());
}
}
http://ifeve.com/promise-future-callback/
https://github.com/hprose/hprose-java/wiki/%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B%E2%80%94%E2%80%94Promise
https://juejin.im/post/5b126065e51d4506bd72b7cc
https://www.infoq.cn/article/design-patterns-promise https://www.cnkirito.moe/future-and-promise/
interface Closure<E, T> {
public T callback(E in);
public void error(Error err);
}
public class Promise<E> {
protected int status = 0;
protected ArrayList<Closure> jobList = new ArrayList<>();
protected Closure<Promise, Void> job;
protected E data;
public Promise(Closure job){
this.job = job;
// 暴露 resolve, reject
this.job.callback(this);
}
private Promise() {
}
public void resolve(E e){
}
public void reject(String err){
}
protected void reject(Error err){
}
public Promise done(Closure c){
return (new Promise<E>());
}
public Promise error(Closure c){
return (new Promise<E>());
}
}
2018年12月21日 星期五
java 非同步做法
public interface Callback<T, E> {
// in: 回傳的資料
public void back(T in);
// 錯誤時要做的事
// err 錯誤訊息
public void error(E err);
}
//----------------------------------------
public class Server_1 {
public Thread asyncGetData(Callback callback) {
out.println("server start");
Thread th_1 = new Thread(() -> {
int time = (int) (Math.random() * 5000);
out.printf("server thread start(%s)\n", time);
try {
Thread.sleep(time);
// 回傳資料
callback.back(time);
out.printf("server thread end(%s)\n", time);
} catch (InterruptedException ex) {
callback.error(ex);
}
});
th_1.start();
return th_1;
}
}
//----------------------------------------
public class Client_1 {
// 資料交換用
int switchData_int;
public void getData(){
out.println("client.getData()");
Server_1 server_1 = new Server_1();
int gg;
Thread th_1 = server_1.asyncGetData(new Callback<Integer, Error>() {
@Override
public void back(Integer in) {
out.println("callback.back");
// 閉包只適用於套嵌的 class
Client_1.this.switchData_int = in;
}
@Override
public void error(Error err) {
}
});
try {
th_1.join();
} catch (InterruptedException ex) {
out.println(ex);
}
out.printf("result(%s)\n------------\n", this.switchData_int);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Client_1 cl = new Client_1();
cl.getData();
cl.getData();
}
}
// in: 回傳的資料
public void back(T in);
// 錯誤時要做的事
// err 錯誤訊息
public void error(E err);
}
//----------------------------------------
public class Server_1 {
public Thread asyncGetData(Callback callback) {
out.println("server start");
Thread th_1 = new Thread(() -> {
int time = (int) (Math.random() * 5000);
out.printf("server thread start(%s)\n", time);
try {
Thread.sleep(time);
// 回傳資料
callback.back(time);
out.printf("server thread end(%s)\n", time);
} catch (InterruptedException ex) {
callback.error(ex);
}
});
th_1.start();
return th_1;
}
}
//----------------------------------------
public class Client_1 {
// 資料交換用
int switchData_int;
public void getData(){
out.println("client.getData()");
Server_1 server_1 = new Server_1();
int gg;
Thread th_1 = server_1.asyncGetData(new Callback<Integer, Error>() {
@Override
public void back(Integer in) {
out.println("callback.back");
// 閉包只適用於套嵌的 class
Client_1.this.switchData_int = in;
}
@Override
public void error(Error err) {
}
});
try {
th_1.join();
} catch (InterruptedException ex) {
out.println(ex);
}
out.printf("result(%s)\n------------\n", this.switchData_int);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Client_1 cl = new Client_1();
cl.getData();
cl.getData();
}
}
2018年12月18日 星期二
javascript 另一種模板編組
function compile(template) {
const evalExpr = /<%=(.+?)%>/g;
const expr = /<%([\s\S]+?)%>/g;
template = template.replace(evalExpr, '`); \n echo( $1 ); \n echo(`');
template = template.replace(expr, '`); \n $1 \n echo(`');
template = 'echo(`' + template + '`);';
console.log(template);
let script =
`let output = "";
function echo(html){
output += html;
}
${template}
return output;`;
return new Function(script);
}
let content = "<ul>\
<% for(let i=0; i < 4; i++){ %>\
<li><%= i %>--${i*2}</li>\
<% } %>\
</ul>";
let res = compile(content);
console.log(res());
console.log('--------------------');
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
https://johnresig.com/blog/javascript-micro-templating/
function compile(template) {
let functionStr = compile_1(template);
functionStr = "data = data || {};\n\
for(let k in data){\n\
let command = 'var '+ k + '= data[\"'+k+'\"];';\n\
eval(command);\n\
}\n\
" + functionStr;
console.log(functionStr);
let fun = new Function('print', 'data', functionStr);
function print(html) {
return html;
}
return (fun).bind(null, print);
}
function compile_1(template) {
const expr = /([\s\S]*?)<%([\s\S]+?)%>/g;
const evalExpr = /([\s\S]*?)<%=([\s\S]+?)%>/g;
reg_1 = /<%[^=-][\s\S]+?%>/;
reg_2 = /<%=[\s\S]+?%>/;
reg_3 = /<%-[^-][\s\S]+?%>/;
let reg = [];
reg.push("(" + reg_1.source + ")");
reg.push("(" + reg_2.source + ")");
reg.push("(" + reg_3.source + ")");
reg = reg.join("|");
reg = `([\\s\\S]*?)(?:${reg})`;
console.log(reg);
reg = RegExp(reg, 'g');
let source = "let source = [];\n";
template = template.replace(reg, function (m, g1, g2, g3, g4) {
debugger;
if (g1) {
source += `source.push(\`${g1}\`);\n`;
}
if (g2) {
// <% %>
g2 = g2.replace(/%>$/, '').replace(/^<%/, '');
source += `\n${g2}\n`;
} else if (g3) {
// <%= %>
g3 = g3.replace(/%>$/, '').replace(/^<%=/, '');
source += `source.push(print(${g3}));\n`;
} else if (g4) {
// <%- %>
g4 = g4.replace(/%>$/, '').replace(/^<%-/, '');
source += `source.push(print(${g4}));\n`;
}
return '';
});
if (template) {
source += `source.push(\`${template}\`);\n`;
}
source += 'return (source.join(""));\n';
return source;
}
let content = "<ul>\
<% for(let i=0; i < a.length; i++){ %>\
<li><%= i*2 %>--${a[i]*2}</li>\
<% } %>\
</ul>";
let res = compile(content);
console.dir(res);
const evalExpr = /<%=(.+?)%>/g;
const expr = /<%([\s\S]+?)%>/g;
template = template.replace(evalExpr, '`); \n echo( $1 ); \n echo(`');
template = template.replace(expr, '`); \n $1 \n echo(`');
template = 'echo(`' + template + '`);';
console.log(template);
let script =
`let output = "";
function echo(html){
output += html;
}
${template}
return output;`;
return new Function(script);
}
let content = "<ul>\
<% for(let i=0; i < 4; i++){ %>\
<li><%= i %>--${i*2}</li>\
<% } %>\
</ul>";
let res = compile(content);
console.log(res());
console.log('--------------------');
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
https://johnresig.com/blog/javascript-micro-templating/
function compile(template) {
let functionStr = compile_1(template);
functionStr = "data = data || {};\n\
for(let k in data){\n\
let command = 'var '+ k + '= data[\"'+k+'\"];';\n\
eval(command);\n\
}\n\
" + functionStr;
console.log(functionStr);
let fun = new Function('print', 'data', functionStr);
function print(html) {
return html;
}
return (fun).bind(null, print);
}
function compile_1(template) {
const expr = /([\s\S]*?)<%([\s\S]+?)%>/g;
const evalExpr = /([\s\S]*?)<%=([\s\S]+?)%>/g;
reg_1 = /<%[^=-][\s\S]+?%>/;
reg_2 = /<%=[\s\S]+?%>/;
reg_3 = /<%-[^-][\s\S]+?%>/;
let reg = [];
reg.push("(" + reg_1.source + ")");
reg.push("(" + reg_2.source + ")");
reg.push("(" + reg_3.source + ")");
reg = reg.join("|");
reg = `([\\s\\S]*?)(?:${reg})`;
console.log(reg);
reg = RegExp(reg, 'g');
let source = "let source = [];\n";
template = template.replace(reg, function (m, g1, g2, g3, g4) {
debugger;
if (g1) {
source += `source.push(\`${g1}\`);\n`;
}
if (g2) {
// <% %>
g2 = g2.replace(/%>$/, '').replace(/^<%/, '');
source += `\n${g2}\n`;
} else if (g3) {
// <%= %>
g3 = g3.replace(/%>$/, '').replace(/^<%=/, '');
source += `source.push(print(${g3}));\n`;
} else if (g4) {
// <%- %>
g4 = g4.replace(/%>$/, '').replace(/^<%-/, '');
source += `source.push(print(${g4}));\n`;
}
return '';
});
if (template) {
source += `source.push(\`${template}\`);\n`;
}
source += 'return (source.join(""));\n';
return source;
}
let content = "<ul>\
<% for(let i=0; i < a.length; i++){ %>\
<li><%= i*2 %>--${a[i]*2}</li>\
<% } %>\
</ul>";
let res = compile(content);
console.dir(res);
2018年11月21日 星期三
json deepCopy
// 比 JSON.parse(JSON.stringify(data)) 還略慢
module.exports = deepCopy;
let jobList = [];
// for test
// 與 JSON.stringify() 對比速度用
function deepCopy(value) {
// debugger;
let dataSet = new DataSet(value);
jobList.push(dataSet);
let index = 0;
while ((dataSet = jobList[index++]) != null) {
// debugger;
let _value = dataSet.originalValue;
if (Array.isArray(_value)) {
for (let i = 0; i < _value.length; i++) {
let v = _value[i];
let ds = new DataSet(v, dataSet, i);
jobList.push(ds);
}
} else if (typeof (_value) == "object") {
for (let k in _value) {
let v = _value[k];
let ds = new DataSet(v, dataSet, k);
jobList.push(ds);
}
} else {
continue;
}
}
//-----------------------
let res;
let d;
while ((d = jobList.pop()) != null) {
res = d;
d.solve();
}
return res.value;
}
//======================================
function DataSet(v, p, k) {
this.parent; // DataSet
this.parentKey;
this.value;
this.originalValue;
this.__construct(v, p, k);
}
(function () {
this.__construct = function (v, p, k) {
this.originalValue = v;
if (p) {
this.parent = p;
this.parentKey = k;
}
this._makeValue();
};
//--------------------------------------
this._makeValue = function () {
if (Array.isArray(this.originalValue)) {
this.value = [];
} else if (typeof (this.originalValue) == "object") {
this.value = {};
} else {
this.value = this.originalValue;
}
};
//--------------------------------------
this.solve = function () {
if (this.parent == null) {
return;
}
let data = this.parent.value;
data[this.parentKey] = this.value;
this._destory();
};
//--------------------------------------
this._destory = function () {
this.parent = undefined;
this.parentKey = undefined;
this.value = undefined;
this.originalValue = undefined;
};
}).call(DataSet.prototype);
module.exports = deepCopy;
let jobList = [];
// for test
// 與 JSON.stringify() 對比速度用
function deepCopy(value) {
// debugger;
let dataSet = new DataSet(value);
jobList.push(dataSet);
let index = 0;
while ((dataSet = jobList[index++]) != null) {
// debugger;
let _value = dataSet.originalValue;
if (Array.isArray(_value)) {
for (let i = 0; i < _value.length; i++) {
let v = _value[i];
let ds = new DataSet(v, dataSet, i);
jobList.push(ds);
}
} else if (typeof (_value) == "object") {
for (let k in _value) {
let v = _value[k];
let ds = new DataSet(v, dataSet, k);
jobList.push(ds);
}
} else {
continue;
}
}
//-----------------------
let res;
let d;
while ((d = jobList.pop()) != null) {
res = d;
d.solve();
}
return res.value;
}
//======================================
function DataSet(v, p, k) {
this.parent; // DataSet
this.parentKey;
this.value;
this.originalValue;
this.__construct(v, p, k);
}
(function () {
this.__construct = function (v, p, k) {
this.originalValue = v;
if (p) {
this.parent = p;
this.parentKey = k;
}
this._makeValue();
};
//--------------------------------------
this._makeValue = function () {
if (Array.isArray(this.originalValue)) {
this.value = [];
} else if (typeof (this.originalValue) == "object") {
this.value = {};
} else {
this.value = this.originalValue;
}
};
//--------------------------------------
this.solve = function () {
if (this.parent == null) {
return;
}
let data = this.parent.value;
data[this.parentKey] = this.value;
this._destory();
};
//--------------------------------------
this._destory = function () {
this.parent = undefined;
this.parentKey = undefined;
this.value = undefined;
this.originalValue = undefined;
};
}).call(DataSet.prototype);
2018年11月20日 星期二
worker 與 java 執行續的不同
worker 父執行緒與子執行緒並不會交叉執行
let child = new Worker("./child_1.js");
let it;
child.onmessage = function(e) {
let data = e.data;
console.log(`child ${data.index}`);
// 確保 parent loop 與 child 幾乎同時執行
it.next();
};
function* parentLoop(){
for (var i = 0; i < 100; i++) {
console.log(`parent ${i}`);
}
console.dir("parent finish");
}
function click() {
it = parentLoop();
child.postMessage({});
}
-----------------------------------------------------------------
onmessage = function(oEvent) {
for (var i = 0; i < 100; i++) {
postMessage({index:i});
}
};
let child = new Worker("./child_1.js");
let it;
child.onmessage = function(e) {
let data = e.data;
console.log(`child ${data.index}`);
// 確保 parent loop 與 child 幾乎同時執行
it.next();
};
function* parentLoop(){
for (var i = 0; i < 100; i++) {
console.log(`parent ${i}`);
}
console.dir("parent finish");
}
function click() {
it = parentLoop();
child.postMessage({});
}
-----------------------------------------------------------------
onmessage = function(oEvent) {
for (var i = 0; i < 100; i++) {
postMessage({index:i});
}
};
2018年11月15日 星期四
2018年11月13日 星期二
java 從網址取得 json data 並解析
package test_4;
import org.json.*;
import java.net.*;
import java.io.*;
import static java.lang.System.out;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author xman
*/
public class T_1 {
public static String getURLContent(String urlPath) throws MalformedURLException, IOException {
String content = "";
HttpURLConnection connection = null;
BufferedReader in;
URL url = null;
url = new URL(urlPath);
URLConnection urlConnection = url.openConnection();
if (urlConnection instanceof HttpURLConnection) {
connection = (HttpURLConnection) urlConnection;
} else {
System.out.println("请输入 URL 地址");
return content;
}
in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String current;
while ((current = in.readLine()) != null) {
content += current;
}
return content;
}
public static void main(String[] args) throws Exception {
String htmlContent = getURLContent("http://localhost:8081/test_1/JSON/t_1.php");
// out.println(htmlContent);
JSONObject j;
j = new JSONObject(htmlContent);
Iterator<String> it = j.keys();;
while (it.hasNext()) {
String key = it.next();
Object o_1 = j.get(key);
out.printf("(%s)=>(%s)\n", key, o_1.toString());
}
}
}
java 閉包 範例
package test_4;
import static java.lang.System.out;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author xman
*/
public class T_2 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int a = 5;
T2_Closure t = (new T2_Closure<Object, Void>() {
@Override
public Void callback(Object in) {
// 引用 a
out.printf("callback(%s)\n", a);
return null;
}
});
t.callback(null);
//------------------------------------
T2_Query q = new T2_Query();
q.query(new T2_Closure<T2_Query, Void>() {
@Override
public Void callback(T2_Query in) {
String res = in.name + " : " + a;
out.println(res);
return null;
}
});
}
}
//--------------------------------------
// 閉包
interface T2_Closure<T, E> {
public E callback(T in);
}
//--------------------------------------
class T2_Query {
String name = "xyz";
void query(T2_Closure closure) {
Thread th = new Thread(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
out.println(e);
}
closure.callback(T2_Query.this);
});
th.start();
out.println("thread start");
}
}
import static java.lang.System.out;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author xman
*/
public class T_2 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int a = 5;
T2_Closure t = (new T2_Closure<Object, Void>() {
@Override
public Void callback(Object in) {
// 引用 a
out.printf("callback(%s)\n", a);
return null;
}
});
t.callback(null);
//------------------------------------
T2_Query q = new T2_Query();
q.query(new T2_Closure<T2_Query, Void>() {
@Override
public Void callback(T2_Query in) {
String res = in.name + " : " + a;
out.println(res);
return null;
}
});
}
}
//--------------------------------------
// 閉包
interface T2_Closure<T, E> {
public E callback(T in);
}
//--------------------------------------
class T2_Query {
String name = "xyz";
void query(T2_Closure closure) {
Thread th = new Thread(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
out.println(e);
}
closure.callback(T2_Query.this);
});
th.start();
out.println("thread start");
}
}
2018年11月10日 星期六
java callback
/**
*
* @author xman
*/
public class Tt {
String name = "......";
void query(Tool t) {
t.set(this);
}
public static void main(String[] args) {
Tt tt = new Tt();
tt.query(new Tool<Tt>() {
public void set(Tt o) {
out.println(o.name);
}
});
tt.query((o) -> {
// error
out.println(o.name);
});
}
}
interface Tool<T> {
public void set(T in);
}
java 非同步呼叫 callback
public class Ajax_1 {
Callback callback;
String name;
void query(Callback callback) {
this.callback = callback;
// 非同步
Thread t = new Thread(() -> {
// 取得查詢
String name = (new SyncSqlQuery()).query();
Ajax_1.this.name = name;
Ajax_1.this.callback.callback();
});
t.start();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Ajax_1 a = new Ajax_1();
int x = 5;
a.query(() -> {
// 及時命令
out.println(a.name);
});
a.query(new Callback(){
public void callback(){
// 及時命令
out.println(a.name);
}
});
}
}
//-------------------------------------------------------
public interface Callback {
void callback();
}
//-------------------------------------------------------
public class SyncSqlQuery {
public static int id = 0;
String query(){
return "SyncSqlQuery_" + id++;
}
}
//////////////////////////////////////////////////////////////////////////
/**
*
* @author xman
*/
public class Ajax_1 {
String name;
void query(Callback callback) {
Thread t = new Thread(() -> {
// 取得查詢
String name = (new SyncSqlQuery()).query();
Ajax_1.this.name = name;
});
t.start();
try {
t.join();
} catch (InterruptedException ex) {
out.println(ex);
}
callback.callback();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Ajax_1 a = new Ajax_1();
int x = 5;
a.query(() -> {
out.println(a.name);
});
a.query(new Callback(){
public void callback(){
out.println(a.name);
}
});
}
}
訂閱:
文章 (Atom)