实例介绍
【实例简介】Java实现区块链,成语接龙实例。
【实例截图】
【核心代码】Java
package tech.topcoder.blockchain; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang.StringUtils; /** * 区块链实现 * */ public class BlockChain { public static List<Block> blockchain = new ArrayList<>(); static final String ipPrev = "192.168.8."; // 对局域网内的电脑进行扫描,找到最长的链,下载到本地 static final String dataFileDir = "c://blockchain"; // 本地存储路径 /** * 创建新块 */ public static Block newBlock(int index, String proof, String hash, Timestamp t, String sender, String recipient) { Block block = null; block = new Block(index, proof, hash, t, sender, recipient); return block; } public static void init() { System.out.println("===>初始化..."); File dirFile = new File(dataFileDir); if (!dirFile.exists()) { dirFile.mkdir(); // 往新创建的本地文件里面写一个创世块 try { FileOutputStream fos = new FileOutputStream(dirFile "//data.txt"); fos.write((BlockChain.createFirstBlock().toInfoString() "\r\n").getBytes("UTF-8")); fos.close(); } catch (Exception e) { } } } /** * Hash一个块 */ public static String hash(Block block) { String hash = null; String s = block.previousHash block.proof block.recipient block.sender block.createTime.toString(); hash = MD5(s); return hash; } /** * 创始块的创建,创世块是一个块,必须是固定的信息 * * 逻辑上来说,只有在区块链产品的第一个用户第一次启动的时候,才会需要创建创世块 */ public static Block createFirstBlock() { try { Timestamp t = new Timestamp( new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2018-01-01 01:01:01").getTime()); return newBlock(0, "海阔天空", "*", t, "*", "*"); } catch (Exception e) { e.printStackTrace(); return null; } } public static String MD5(String key) { char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; try { byte[] btInput = key.getBytes(); // 获得MD5摘要算法的 MessageDigest 对象 java.security.MessageDigest mdInst = java.security.MessageDigest.getInstance("MD5"); // 使用指定的字节更新摘要 mdInst.update(btInput); // 获得密文 byte[] md = mdInst.digest(); // 把密文转换成十六进制的字符串形式 int j = md.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i ) { byte byte0 = md[i]; str[k ] = hexDigits[byte0 >>> 4 & 0xf]; str[k ] = hexDigits[byte0 & 0xf]; } return new String(str); } catch (Exception e) { return null; } } /** * 验证当前的成语是否符合规则 * * @param prev * 前一个成语 * @param current * 当前成语 */ public static boolean validProof(String prev, String current) { // 验证这个成语的头一个字是不是上一个成语的最后一个字 if (current.charAt(0) != prev.charAt(prev.length() - 1)) { return false; } try { String content = httpRequest( "http://chengyu.t086.com/chaxun.php?q=" URLEncoder.encode(current, "gb2312") "&t=ChengYu", 5000, "gbk"); if (content == null || content.indexOf("没有找到与您搜索相关的成语") != -1 || content.indexOf("搜索词太长") != -1) { return false; } else { return true; } } catch (Exception e) { e.printStackTrace(); return false; } } public static String httpRequest(String urlAddr, int connectTimeout) { return httpRequest(urlAddr, connectTimeout, null); } public static String httpRequest(String urlAddr, int connectTimeout, String charset) { InputStream iStream = null; try { URL url = new URL(urlAddr); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); if (connectTimeout > 0) { connection.setConnectTimeout(connectTimeout); } if (connection.getResponseCode() == 200) { iStream = connection.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int len = 0; while ((len = iStream.read(buf)) != -1) { baos.write(buf, 0, len); baos.flush(); } if (charset != null) { return baos.toString(charset); } else { return baos.toString("UTF-8"); } } } catch (Exception e) { } finally { if (iStream != null) { try { iStream.close(); } catch (Exception ex) { } } } return null; } /** * 从网络读取区块链数据到本地文件 */ public static void downloadData() { File dirFile = new File(dataFileDir); if (!dirFile.exists()) { dirFile.mkdir(); // 往新创建的本地文件里面写一个创世块 try { FileOutputStream fos = new FileOutputStream(dirFile "//data.txt"); fos.write((BlockChain.createFirstBlock().toInfoString() "\r\n").getBytes("UTF-8")); fos.close(); } catch (Exception e) { } } // 扫描周边的节点,找到最长的链,下载到本地 int lastLen = 0; String lastChain = ""; for (int i = 0; i < 255; i ) { String url = "http://" ipPrev i ":8080/blockchain/chain.jsp"; System.out.println(url); String chain = httpRequest(url, 10); if (chain != null && chain.length() > 0) { chain = chain.trim(); System.out.println(chain); String[] temp = StringUtils.splitByWholeSeparator(chain, "##"); if (temp.length > lastLen) { lastLen = temp.length; lastChain = chain; } } } try { if (lastChain != "") { FileOutputStream fos = new FileOutputStream(dirFile "//data.txt"); fos.write((lastChain.replace("##", "\r\n") "\r\n").getBytes("UTF-8")); fos.close(); } } catch (Exception e) { } } public static String stringBlockChain() { try { FileInputStream fis = new FileInputStream(new File(dataFileDir "//data.txt")); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int len = 0; while ((len = fis.read(buf)) != -1) { baos.write(buf, 0, len); baos.flush(); } fis.close(); String chain = baos.toString("UTF-8"); return StringUtils.join(chain.split("\r\n"), "##"); } catch (Exception e) { return ""; } } public static void loadData() { String chain = stringBlockChain(); String[] chains = StringUtils.splitByWholeSeparator(chain, "##"); blockchain.clear(); for (String s : chains) { String[] temp = StringUtils.split(s, "#"); String[] time = StringUtils.split(temp[3], "."); Timestamp t = new Timestamp(DateUtil.parse(time[0]).getTime()); Block block = newBlock(Integer.valueOf(temp[0]), temp[1], temp[2], t, temp[4], temp[5]); blockchain.add(block); } } public static void writeData() { try { List<String> chains = new ArrayList<>(); for (Block block : blockchain) { chains.add(block.toInfoString()); } FileOutputStream fos = new FileOutputStream(dataFileDir "//data.txt"); fos.write((StringUtils.join(chains, "\r\n") "\r\n").getBytes("UTF-8")); fos.close(); } catch (Exception e) { } } }
好例子网口号:伸出你的我的手 — 分享!
相关软件
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论