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("异常关闭 !!!");
        }
      }
    }
  • 相关阅读:
    面向对象三大特征------多态
    接口的概念
    面向对象(抽象类)
    面向对象三大特征------继承
    面向对象三大特征------封装
    成员变量和局部变量的区别
    20180822 ajax post 方式请求
    20180815 权限
    20180815 视图
    20180814 夜晚小目标
  • 原文地址:https://www.cnblogs.com/wudeyun/p/14182084.html
Copyright © 2011-2022 走看看