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("异常关闭 !!!");
        }
      }
    }
  • 相关阅读:
    AIX 日常维护
    复制百度文库的方法
    linux free命令详解
    Oracle中Kill session的研究
    oracle scn的研究转自听海日志
    Win7无法待机(休眠)的一种可能原因
    vmstat命令详解
    winform与数据库同步更新
    CAD—Keyboard事件处理
    游戏之寻路算法
  • 原文地址:https://www.cnblogs.com/wudeyun/p/14182084.html
Copyright © 2011-2022 走看看