zoukankan      html  css  js  c++  java
  • Socket Channels 客户端服务端示例

    Server 端,主要代码,这里 ServerSocketChannel 采用非阻塞模式,消息均不超过 1024 字节

    public class Server{
    
      public static void main(String[] arg) {
    
        try (ServerSocketChannel ssc = ServerSocketChannel.open()) {
          ssc.configureBlocking(false);
          ssc.bind(new InetSocketAddress("localhost", 9999));
          System.out.println("启动成功 ...");
          String msg = "server message ";
    
          while (true) {
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            try (SocketChannel sc = ssc.accept()) {
              if (null == sc) {
                log.info("空轮询 ...");
                Thread.sleep(2000);
                continue;
              }
    
              while (true) {
                byteBuffer.put((msg + System.currentTimeMillis()).getBytes());
                byteBuffer.flip();
                sc.write(byteBuffer);
                byteBuffer.clear();
    
                if (sc.read(byteBuffer) > 0) {
                  System.out.println(new String(byteBuffer.array(), 0, byteBuffer.position()));
                  byteBuffer.clear();
                }
    
                Thread.sleep(1000);
              }
            } catch (Exception e) {
              log.info("处理请求时异常 !!!");
            }
          }
        } catch (Exception e) {
          log.error("异常关闭 !!!");
        }
      }
    }

    Client 端,主要代码

    @Slf4j(topic = "c.Client")
    public class Client {
    
      public static void main(String[] args) {
        try (SocketChannel sc = SocketChannel.open()) {
          sc.bind(new InetSocketAddress(8888));
          sc.connect(new InetSocketAddress("localhost", 9999));
          ByteBuffer byteBuffer = ByteBuffer.allocate(200);
    
          while (sc.read(byteBuffer) > 0) {
            byteBuffer.flip();
            System.out.println(new String(byteBuffer.array(), 0, byteBuffer.limit()));
            sc.write(byteBuffer);
            byteBuffer.clear();
          }
        } catch (Exception e) {
          log.error("异常关闭 !!!");
        }
      }
    }
  • 相关阅读:
    JS运算符
    JS基础
    0507-弹性盒子
    0506css3(2D、3D)动画
    CSS3边框
    0503-格式与布局
    0502-边框边界
    0502-其他html标签
    0428-专题块状元素
    mysql 数据库学习
  • 原文地址:https://www.cnblogs.com/wudeyun/p/14182084.html
Copyright © 2011-2022 走看看