您现在的位置是:首页 > 文章详情

smart-socket v1.4.8 发布,国产 Java AIO 通信框架

日期:2020-02-23点击:332

smart-socket 是一款国产开源的 Java AIO 框架,追求代码量、性能、稳定性、接口设计各方面都达到极致。如果 smart-socket 对您有一丝帮助,请 Star 一下我们的项目并持续关注;如果您对 smart-socket 并不满意,那请多一些耐心,smart-socket 一直在努力变得更好。

Maven

 <!-- https://mvnrepository.com/artifact/org.smartboot.socket/aio-core --> <dependency> <groupId>org.smartboot.socket</groupId> <artifactId>aio-core</artifactId> <version>1.4.8</version> </dependency> 

更新内容:

  1. 重构服务端线程模型,相比之前版本简化很多。
  2. 服务端支持自定义 backlog。
  3. 新增状态机:ACCEPT_EXCEPTION,当服务端处理客户端的 accpet 事件异常时触发。
  4. 其他代码上小优化。

快速上手:

  1. 定义协议 
     public class StringProtocol implements Protocol<String> { @Override public String decode(ByteBuffer readBuffer, AioSession<String> session) { byte length = readBuffer.get(readBuffer.position()); if (length+1 < readBuffer.remaining()) { return null; } byte[] b = new byte[readBuffer.get()]; readBuffer.get(b); return new String(b); } }

     

  2. 启动服务端

     public class Server { public static void main(String[] args) throws IOException { AioQuickServer<String> server = new AioQuickServer<String>(8080, new StringProtocol(), new MessageProcessor<String>() { public void process(AioSession<String> session, String msg) { System.out.println("接受到客户端消息:" + msg); byte[] response = "Hi Client!".getBytes(); byte[] head = {(byte) response.length}; try { session.writeBuffer().write(head); session.writeBuffer().write(response); } catch (IOException e) { e.printStackTrace(); } } public void stateEvent(AioSession<String> session, StateMachineEnum stateMachineEnum, Throwable throwable) { } }); server.start(); } }

     

  3. 启动客户端
     public class Client { public static void main(String[] args) throws InterruptedException, ExecutionException, IOException { AioQuickClient<String> client = new AioQuickClient<String>("127.0.0.1", 8080, new StringProtocol(), new MessageProcessor<String>() { public void process(AioSession<String> session, String msg) { System.out.println(msg); } public void stateEvent(AioSession<String> session, StateMachineEnum stateMachineEnum, Throwable throwable) { } }); AioSession<String> session = client.start(); byte[] msgBody = "Hello Server!".getBytes(); byte[] msgHead = {(byte) msgBody.length}; try { session.writeBuffer().write(msgHead); session.writeBuffer().write(msgBody); session.writeBuffer().flush(); } catch (IOException e) { e.printStackTrace(); } } }

     

想要从事物联网开发,又苦于某些通信框架学习成本太高的朋友,不妨来试试 smart-socket。

原文链接:https://www.oschina.net/news/113564/smart-socket-1-4-8-released
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章