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("异常关闭 !!!");
        }
      }
    }
  • 相关阅读:
    关于微软 2012 暑期实习题第 5 题
    ZOJ 1608. Two Circles and a Rectangle
    在技术社区以外的博文中插入代码(把代码转换到 Html 文本)
    ZOJ 2240. Run Length Encoding
    C++中“引用”的底层实现
    采用路径模型实现遍历二叉树的方法
    ZOJ 简单题集合(四)
    ZOJ 3603. Draw Something Cheat
    关于类的虚函数表
    ZOJ 3499. Median
  • 原文地址:https://www.cnblogs.com/wudeyun/p/14182084.html
Copyright © 2011-2022 走看看